import { NotificationsComponent } from 'src/app/core/notifications/notifications.component';
import { Component, OnInit, SecurityContext, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { HttpErrorResponse } from '@angular/common/http';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

import { Post, User } from '../core/entities';
import { PostService } from './post.service';
import { AuthService } from '../core/services/auth.service';

declare let Prism: any;

@Component({
	selector: 'app-post',
	templateUrl: './post.component.html',
	styles: [`
		.author-img {
			width: 60px;
			height: 60px;
			border-radius: 50%;
			margin-right: 15px;
		}
		.card .card-data {
			padding: 15px;
			background-color: #f5f5f5;
		}
		#content {
			margin-bottom: 50px;
		}
		.creation-date-area {
			color: #bdbdbd;
			font-style: italic;
		}
	`]
})
export class PostComponent implements OnInit {
	post: Post = new Post('', '', '', '', '', null, new User('', '', '', '', '', null, null, ''), null);
	loaded: boolean;
	notFound: boolean;
	owned: boolean;

	@ViewChild('alertDelete', {static: false}) alertDelete;

	constructor(
		private activatedRoute: ActivatedRoute,
		private router: Router,
		private postService: PostService,
		private sanitizer: DomSanitizer,
		private authService: AuthService
	) {
		this.loaded = false;
		this.owned = false;
	}

	ngOnInit(): void {
		this.postService.getPost(this.activatedRoute.snapshot.paramMap.get('postKey')).subscribe(post => {
			this.post = post;
			this.loaded = true;
			this.owned = this.isOwned();
			setTimeout(() => {
				Prism.highlightAll();
			}, 100);
		}, error => {
			if (error instanceof HttpErrorResponse && error.status === 404) {
				this.notFound = true;
			}
		});
	}

	private isOwned(): boolean {
		let result = false;

		const connectedUser = this.authService.getUser();
		if (connectedUser) {
			result = this.post.author.key === connectedUser.key;
		}

		return result;
	}

	getContent(): SafeHtml {
		return this.sanitizer.sanitize(SecurityContext.HTML, this.post.text);
	}

	getAvatarUrl(): string {
		return this.post.author.image
				? `./api/images/loadAvatar/${this.post.author.image}`
				: './assets/images/default_user.png';
	}

	deletePost(): void {
		this.postService.deletePost(this.post).subscribe(() => {
			NotificationsComponent.success('Article supprimé.');
			this.alertDelete.hide();
			this.router.navigate(['/myPosts']);
		}, error => {
			console.error(error);
			NotificationsComponent.error('Une erreur est survenue lors de la suppression de l\'article.');
		});
	}
}
