import {Component, Inject, LOCALE_ID, OnDestroy, OnInit} from '@angular/core';
import {
  Crop,
  Keyword,
  Language,
  PageableResource,
  Pest,
  Project,
  Region,
  Resource,
  ResourceType,
  Sector
} from "../../model/resource";
import {ResourceService} from "../../service/resource.service";
import {Message, MessageService} from "primeng/api";
import {environment} from "../../../environments/environment";
import {SearchModel} from "../../model/search-model";
import {NavigationEnd, Router} from "@angular/router";

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit{
  resources: Resource[] = [];
  totalResources: Resource[] = [];
  search:boolean=false;
  pageableResponse?: PageableResource;
  pageSize = 10;
  totalElements: number = 0;
  sectors: Sector[] = [];
  regions: Region[] = [];
  projects: Project[] = [];
  crops:Crop[] = [];
  pests: Pest[] = [];
  pestType: object[] = [{name:"weeds"}, {name:"disease"},{name:"invertebrate"}];
  contentTypes: ResourceType[] = [];
  languages: Language[] = [];
  keywords: Keyword[] = [];
  disclaimer: Message[] = [];
  selectedSectors: Sector[] = [];
  selectedRegions: Region[] = [];
  selectedTypes: ResourceType[] = [];
  selectedLanguages: Language[] = [];
  selectedProjects: Project[] = [];
  selectedCrops: Crop[] = [];
  selectedPests:Pest[] = [];
  selectedPestType: string | undefined;
  serachRunning= false;
  searchTerm: string = "";
  more= true;
  close = false;
  imagePath = environment.baseUrl+"/resource/image";
  imagePathRaw = environment.baseUrl+"/resource/image/raw";
  searchModel:SearchModel = {};
  loading:boolean = true;
  counter:number = 0;
  constructor(private resourceService:ResourceService, private router:Router,private messageService: MessageService, @Inject(LOCALE_ID) public locale: string) {
    this.pageableResponse = {totalElements:0}
  }

  ngOnInit(): void {
    this.resourceService.getAllProjects().subscribe((projects: Project[]) => {
      this.projects = projects;});
    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.contentTypes = contentTypes;});
    this.resourceService.getAllLanguages().subscribe((languages: Language[]) => {
      this.languages = languages;});
    this.resourceService.getAllPests().subscribe((pests: Pest[]) => {
      this.pests = pests;});
    this.resourceService.getAllCrops().subscribe((crops: Crop[]) => {
      this.crops = crops;});
    this.resourceService.getAllResources().subscribe((resources: PageableResource) => {
      // @ts-ignore
      this.resources = resources.content;
      // @ts-ignore
      this.totalElements = resources.totalElements;
      this.search = false;
      this.serachRunning=false;
    });
    }
  public closeDisclaimer(){
    this.close = true;
  }
    public toggleFilters(){
    //kada se zatvore dodatni filteri isprazniti ako je nesto bilo selektovano u tim filterima
    this.more = !this.more;
    }
    public searchResource(){
      // @ts-ignore
      this.serachRunning = true;
      this.resourceService.searchResource(this.searchModel).subscribe((resources: Resource[]) => {
        this.resources = resources;
        this.totalResources = resources;
        this.totalElements = resources.length
        this.search = true;
        this.serachRunning=false;
      },error => {
        this.messageService.add({severity: 'error', detail: 'Some error occurred!'})
        this.serachRunning=false;
      });
    }

  onPageChange(event:any) {
    if (this.search === false){
      var pNum = event.first / event.rows
      this.resourceService.getAllResources(pNum, event.rows,)
      .subscribe(ret => this.populate(ret));
    }else {
      this.resources = this.totalResources.slice(event.first, this.totalResources.length)
    }
  }
  populate(ret: PageableResource) {
    this.pageableResponse = ret;
    // @ts-ignore
    this.resources = this.pageableResponse?.content;
    // @ts-ignore
    this.totalElements = this.pageableResponse.totalElements;
  }
  public resetSearch(){
    this.router.navigate(['home']);

    /*this.serachRunning=true;
    this.resourceService.getAllResources().subscribe((resources: PageableResource) => {
      // @ts-ignore
      this.resources = resources.content;
      // @ts-ignore
      this.totalElements = resources.totalElements;
      this.searchModel = {};
      this.search = false;
      this.serachRunning=false;*/

    //});
  }
  isEmptySearch(){
    return JSON.stringify(this.searchModel) === '{}';
  }
  public getRegion(resource:Resource){
    if (resource.regions !== undefined && resource.regions?.length >1){
      return "EU"
    }else if (resource.regions?.length ===1){
      // if(this.locale !== 'en'){
      //   return Reflect.get(resource.regions[0],'name_'+this.locale)
      // }else{
        return resource.regions[0].name;
      //}
    }else{
      return "EU"
    }
  }
  public getResourceType(resource:Resource){
      // if(this.locale !== 'en'){
      //   // @ts-ignore
      //   return Reflect.get(resource.resourceType,'name_'+this.locale)
      // }else{
        // @ts-ignore
        return resource.resourceType.name;
     // }
  }
  public getProject(resource:Resource){
    if (resource.sectors == undefined|| resource.sectors.length==0 ){
      return null;
    }else{
      return resource.project;
    }
  }
  public getLang(){
    if (this.searchModel.language !=undefined){
      return this.searchModel.language[0].code;
    }
    return "";
  }
}
