import {Component, Inject, LOCALE_ID, OnInit} from '@angular/core';
import {ResourceType, Language, Region, Sector, Project, Resource, Pest, Crop, Link} from "../../model/resource";
import {ResourceService} from "../../service/resource.service";
import {ConfirmationService, MessageService} from 'primeng/api';
import {ActivatedRoute, Router} from "@angular/router";
import {FormControl} from "@angular/forms";
import {environment} from "../../../environments/environment";


@Component({
  selector: 'app-add-resource',
  templateUrl: './add-resource.component.html',
  styleUrls: ['./add-resource.component.css']
})
export class AddResourceComponent implements OnInit {
  sectors: Sector[] = [];
  regions: Region[] = [];
  resourceTypes: ResourceType[] = [];
  languages: Language[] = [];
  projects: Project[] = [];
  pests:Pest[] = [];
  crops: Crop [] = [];
  resource: Resource = {};
  image: any;
  resourceContent: File[] = [];
  displayPestModal=false;
  displayCropModal=false;
  newPest:Pest = {};
  newCrop: Crop = {};
  resourceControl = new FormControl('');
  resourceId?:string;
  edit:boolean = false;
  imageExist:boolean = false;
  imagePath = environment.baseUrl+"/resource/image/raw";
  showOldImg = true;
  logo: any;
  showOldLogo = true;
  logoExist:boolean = false;
  displayTerms = false;
  termChecked = false;
  constructor(private resourceService:ResourceService, private route: ActivatedRoute, private messageService: MessageService, private router: Router, @Inject(LOCALE_ID) public locale: string, private confirmationService: ConfirmationService) { }

  ngOnInit(): void {
    this.resourceService.getAllSectors().subscribe((sectors: Sector[]) => {
      this.sectors = sectors;});
    this.resourceService.getAllRegions().subscribe((regions: Region[]) => {
      this.regions = regions;});
    this.resourceService.getAllResourceTypes().subscribe((contentTypes: ResourceType[]) => {
      this.resourceTypes = contentTypes;});
    this.resourceService.getAllLanguages().subscribe((languages: Language[]) => {
      this.languages = languages;});
    this.resourceService.getAllProjects().subscribe((projects: Project[]) => {
      this.projects = projects;});
    this.resourceService.getAllPests().subscribe((pests: Pest[]) => {
      this.pests = pests;});

    this.resourceService.getAllCrops().subscribe((crops: Crop[]) => {
      this.crops = crops;});

    // @ts-ignore
    this.resourceId = this.route.snapshot.paramMap.get('id');
    if(this.resourceId != undefined){
      // @ts-ignore
      this.resourceService.getResource(this.resourceId).subscribe(data =>{
        this.resource = data;
        this.edit = true;
      });
      this.resourceService.hasImage(this.resourceId,"image").subscribe( data =>{
        this.imageExist = data
      });
      this.resourceService.hasImage(this.resourceId,"logo").subscribe( data =>{
        this.logoExist = data
      });
    }else{
      this.resource.links = []
      this.resource.links.push({name:"",url:""})
    }

  }

  saveResource(){
    this.resource.canEdit=true;
    this.resourceService.saveResource(this.resource,this.edit).subscribe((data: Resource) => {
      this.resource = data;
      this.resourceService.addFiles(this.image, this.logo, this.resourceContent, this.resource.idResource).subscribe(data => {
          if(!this.edit){
            this.messageService.add({severity: 'success', detail: 'Resource is saved, but need to be approved by administrator!'});
            this.router.navigate(['/home']);
          }else{
            this.messageService.add({severity: 'success', detail: 'Resource is updated!'});
            this.router.navigate(['/resource/'+this.resourceId]);
          }

        }, error => {
          this.messageService.add({severity: 'error', detail: 'Some error occurred!'})
        });
    },error => {
      //TODO obrisati sve fajlove koji su se mozda sacuvali ako je doslo do greske
      this.messageService.add({severity: 'error', detail: 'Some error occurred!'})
    });
    }

  public fileUploader(type:string,event:any){
    if(type === 'image'){
        this.image = event.files[0]
    }
    else if(type === 'logo'){
      this.logo = event.files[0]
    }
    else{
      this.resourceContent = event.files;
    }
  }
  public openPestModal(){
    // @ts-ignore
    if (this.resource.pests.filter(e => e.commonName === 'Other').length > 0) {
      this.displayPestModal=true;
    }
  }

  public addPest(){
    // @ts-ignore
    var selectedPests = this.resource.pests.filter(function(el) { return el.commonName != "Other"; });
    this.resource.pests = selectedPests;
    this.resource.pests.push(this.newPest);
    this.pests.push(this.newPest);
    this.resourceService.addCrop(this.newPest).subscribe()
    this.newPest={};
    this.displayPestModal=false;
  }

  public openCropModal(){
    // @ts-ignore
    if (this.resource.crops.filter(e => e.commonName === 'Other').length > 0) {
      this.displayCropModal=true;
    }
  }

  public addCrop(){
    // @ts-ignore
    var selectedCrops = this.resource.crops.filter(function(el) { return el.commonName != "Other"; });
    this.resource.crops = selectedCrops;
    this.resource.crops.push(this.newCrop);
    this.crops.push(this.newCrop);
    this.resourceService.addCrop(this.newCrop).subscribe()
    this.newCrop={};
    this.displayCropModal=false;
  }
  hideOldImage(){
    this.showOldImg = false;
  }
  removeImage(){
    this.image=undefined;
    this.showOldImg = true;
  }
  hideOldLogo(){
    this.showOldLogo = false;
  }
  removeLogo(){
    this.logo=undefined;
    this.showOldLogo = true;
  }
  showTerms(){
    this.displayTerms = true;
  }
  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(['/resource/edit/'+this.resource.idResource]);
          }, error => {
            this.messageService.add({severity: 'error', detail: 'Some error occurred!'});
          }
        );
      }
    });
  }
  downloadFile(fileName: any): void {
    this.resourceService.downloadFile(fileName).subscribe((file: any) => {
      const blob = new Blob([file], {type: file.type});

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

  addNewLink() {
    // @ts-ignore
    this.resource.links.push({
      name: "",
      url: "",
    });
  }

  removeLink( linkIndex: number) {
    // @ts-ignore
    this.resource.links.splice(linkIndex, 1);
  }
  track(index: number, item: Link) {
    return index;
  }
}
