import { Component, OnInit } from '@angular/core';
import {ResourceService} from "../../service/resource.service";
import {ActivatedRoute, Router} from "@angular/router";
import {environment} from "../../../environments/environment";
import {Comment, Resource} from "../../model/resource";
import {ConfirmationService, MessageService} from "primeng/api";
import {Observable} from "rxjs";
import {User} from "../../model/user";
import {UserState} from "../../states/user.state";
import {Store} from "@ngxs/store";
import {HttpResponse} from "@angular/common/http";
import {DomSanitizer, SafeResourceUrl} from '@angular/platform-browser';

@Component({
  selector: 'app-resource',
  templateUrl: './resource.component.html',
  styleUrls: ['./resource.component.css']
})
export class ResourceComponent implements OnInit {
  resource: Resource ={};
  imagePath = environment.baseUrl+"/resource/image";
  filePath = environment.baseUrl+"/resource/file";
  url:any;
  resourceId = null;
  lang = null;
  displayModal=false;
  copiedLink="";
  comment:Comment = {text:"",commenterEmail:""};
  displayCommentModal = false;
  safeURL?:SafeResourceUrl;
  displayPreviewModal = false
  selectedFile= ""
  // @ts-ignore
  public loggeduser: Observable<User> = this.store.select(UserState.userDetails);

  constructor(private resourceService:ResourceService, private route: ActivatedRoute, private sanitizer:DomSanitizer,
              private router: Router, private store:Store, private messageService:MessageService, private confirmationService: ConfirmationService) { }

  ngOnInit(): void {
    // @ts-ignore
    this.resourceId = this.route.snapshot.paramMap.get('id');
    // @ts-ignore
    this.lang = this.route.snapshot.paramMap.get('lang');

    // @ts-ignore
     this.resourceService.getResource(this.resourceId,this.lang).subscribe(data =>{
       this.resource =data;
       if (this.resource.youtube !=undefined){

         this.safeURL = this.sanitizer.bypassSecurityTrustResourceUrl(this.resource.youtube.replace('watch?v=','embed/'));

       }
     });
  }
  downloadFile(fileName: any): void {
    this.resourceService.downloadFile(fileName).subscribe((file: any) => {
      const blob = new Blob([file], {type: file.type});

      this.url = window.URL.createObjectURL(blob);
      /*const link = document.createElement('a');
      link.href = this.url;
      link.target="_blank";
      link.download = fileName;*/
      window.open(this.url,"_blank")
    }, error => {
      console.log(error)
    });
  }


  approve(event: Event) {
    this.confirmationService.confirm({
      message: 'Are you sure that you want to approve resource?',
      icon: 'pi pi-exclamation-triangle',
      accept: () => {
        // @ts-ignore
        this.resourceService.approveResource(this.resourceId).subscribe(r =>{
          this.messageService.add({severity:'success', detail:'Resource has been approved.'});
          this.router.navigate(['/home'])
        },error =>{
          this.messageService.add({severity:'error', detail:'Some error occured!'});
        }
      );
      }
      });
  }
  archive(event: Event) {
    this.confirmationService.confirm({
      message: 'Are you sure that you want to archive resource?',
      icon: 'pi pi-exclamation-triangle',
      accept: () => {
        // @ts-ignore
        this.resourceService.archiveResource(this.resourceId).subscribe(r => {
            this.messageService.add({severity: 'success', detail: 'Resource has been archived.'});
            this.router.navigate(['/home'])
          }, error => {
            this.messageService.add({severity: 'error', detail: 'Some error occured!'});
          }
        );
      }
    });
  }
  delete(event: Event) {
    this.confirmationService.confirm({
      message: 'Are you sure that you want to delete resource?',
      icon: 'pi pi-exclamation-triangle',
      accept: () => {
        // @ts-ignore
        this.resourceService.deleteResource(this.resourceId).subscribe(r =>{
            this.messageService.add({severity:'success', detail:'Resource has been deleted.'});
            this.router.navigate(['/home'])
          },(error: { status: any; }) =>{
            this.messageService.add({severity:'error', detail:'Some error occurred!'});
          }
        );
      }
    });
  }
  showInfo() {
    this.messageService.add({severity:'info', summary: 'Info', detail: 'This feature has not been implemented yet!'});
  }
  getPermLink(resourceId: string|undefined) {
    if(resourceId != undefined){
      return location.origin + '/toolbox/#/resource/' + resourceId;
    }else{
      return location.origin + '/toolbox/#/home';
    }
  }

  linkCopied(link: string) {
      this.copiedLink=link;
      this.displayModal=true;
  }

  download(resource:Resource) {
    this.resourceService.download(resource).subscribe({
      next: (data) => {
        // @ts-ignore
        if (resource.resourceName ==undefined){
          resource.resourceName = "unknown"
        }
        this.downloadPDF(data as unknown as HttpResponse<any>, resource.resourceName)
      },
      error: () => {
        this.messageService.add({severity:'error', detail:'Some error occurred!'});
      }
    });
  }
  private downloadPDF(resp: HttpResponse<any>,fileName:string) {
    const content = resp.headers.get('Content-Type');
    const blob = new Blob([resp.body], { type: resp.body.type });
    const anchor = document.createElement('a');
    anchor.href = window.URL.createObjectURL(blob);
    anchor.download = fileName +'.pdf';
    anchor.target = '_blank';
    anchor.dataset.downloadurl = ['text/plain', anchor.download, anchor.href].join(':');
    document.body.appendChild(anchor);
    anchor.click();
    document.body.removeChild(anchor);
  }

  public toogleCommentModal(){
    // @ts-ignore
    this.displayCommentModal = !this.displayCommentModal;
    this.comment.text=""
    this.comment.commenterEmail=""

  }
  public sendEmail(){
      // @ts-ignore
    this.resourceService.sendEmail(this.resource.idResource,this.comment).subscribe( r =>{
      this.toogleCommentModal();
      this.messageService.add({severity: 'success', detail: 'Your comment is sent to email IPMWORKS-WP4@inrae.fr.'});

    })
  }

}
