import { Component, OnInit } from '@angular/core';
import {ResourceService} from "../../service/resource.service";
import {FileDesc} from "../../model/resource";
import {Observable} from "rxjs";
import {User} from "../../model/user";
import {UserState} from "../../states/user.state";
import {Store} from "@ngxs/store";
import {ConfirmationService, MessageService} from "primeng/api";
import {Router} from "@angular/router";

@Component({
  selector: 'app-help',
  templateUrl: './help.component.html',
  styleUrls: ['./help.component.css']
})
export class HelpComponent implements OnInit {
  helpFilesDesc: FileDesc[] = [];
  url: any;
  newFile: FileDesc = {};
  displayFileModal = false;
  fileContent: any;


  // @ts-ignore
  public loggeduser: Observable<User> = this.store.select(UserState.userDetails);

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

  ngOnInit(): void {
    this.resourceService.getAllHelpFilesDesc().subscribe((files: FileDesc[]) => {
      this.helpFilesDesc = files;
    });
  }

  downloadFile(fileId: any): void {
    this.resourceService.downloadFileById(fileId).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)
    });
  }

  delete(fileId?: String) {
    this.confirmationService.confirm({
      message: 'Are you sure that you want to delete resource?',
      icon: 'pi pi-exclamation-triangle',
      accept: () => {
        // @ts-ignore
        this.resourceService.deleteFile(fileId).subscribe(r => {
            this.messageService.add({severity: 'success', detail: 'Resource has been deleted.'});
            this.router.navigate(['/help']);
          }, error => {
            this.messageService.add({severity: 'error', detail: 'Some error occurred!'});
          }
        );
      }
    });
  }

  public fileUploader(event: any) {
    this.fileContent = event.files[0];
  }

  public addFile() {
    // @ts-ignore
    this.resourceService.addFile(this.fileContent, this.newFile.description, "help").subscribe(data => {
        this.messageService.add({severity: 'success', detail: 'File is added!'});
      this.router.navigate(['/help']);

    }, error => {
      this.messageService.add({severity: 'error', detail: 'Some error occurred!'})
    });
  }

  public removeFile(){
    this.fileContent=undefined;
  }
  public isEmpty(){
    if (this.newFile.description && this.fileContent){
      return false;
    }else{
      return true;
    }
  }
}
