import { Component, OnInit } from '@angular/core';
import {ResourceType, Language, Region, Sector, Project, Resource, Pest, Crop} from "../../model/resource";
import {ResourceService} from "../../service/resource.service";
import {MessageService} from 'primeng/api';
import {Router} from "@angular/router";


@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[] = [];
  constructor(private resourceService:ResourceService,private messageService: MessageService, private router: Router) { }

  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;});
  }

  saveResource(){
    this.resourceService.saveResource(this.resource).subscribe((data: Resource) => {
      this.resource = data;
      this.resourceService.addFiles(this.image,this.resourceContent,this.resource.idResource).
        subscribe(data =>{
          this.messageService.add({severity:'success', detail:'Resource is saved!'});
          this.router.navigate(['/home']);

      },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{
      this.resourceContent = event.files;
    }
  }


}
