import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { ModalController } from '@ionic/angular';
import { Publication } from 'src/app/models/publication';
import { PublicationFolder } from 'src/app/models/publicationfolder';
import { LoadingService } from 'src/app/services/loading.service';
import { PublicationsService } from 'src/app/services/publications.service';

import { NewPublicationPage } from 'src/app/pages/publications/new-publication/new-publication.page';
import { PublicationListStorage } from 'src/app/store/publication-list.service'
import { PublicationEventFolderStorage } from 'src/app/store/publication-event-folder.service';
import { PublicationTravelFolderStore } from 'src/app/store/publication-travel-folder.service';
import { PublicationPipe } from 'src/app/pipes/publication.pipe';
import { ThemeService } from 'src/app/services/theme.service'
import { ToastService } from 'src/app/services/toast.service';
import { EditActionPage } from 'src/app/pages/publications/edit-action/edit-action.page';

@Component({
  selector: 'app-view-publications',
  templateUrl: './view-publications.page.html',
  styleUrls: ['./view-publications.page.scss'],
})
export class ViewPublicationsPage implements OnInit {
  showLoader: boolean;
  loading: any;

  publicationList: Publication[];
  item: PublicationFolder;

  error: any;

  @Input() folderId: string;
  @Output() addNewPublication =  new EventEmitter<any>();
  @Output() editPublication =  new EventEmitter<any>();
  @Output() openPublicationDetails= new EventEmitter<any>();
  @Output() goBackToViewPublications = new EventEmitter();
  @Output() closeDesktopComponent =  new EventEmitter<any>();
  @Output() goBacktoPublicationDetails = new EventEmitter<any>();


  publicationListStorage = PublicationListStorage
  //
  publicationEventFolderStorage = PublicationEventFolderStorage
  publicationTravelFolderService = PublicationTravelFolderStore

  publicationPipe = new PublicationPipe()

  constructor(
    private loadingController: LoadingService,
    private modalController: ModalController,
    private publications: PublicationsService,
    public ThemeService: ThemeService,
    private toastService: ToastService,
    ) {
      this.item = new PublicationFolder();
  }

  ngOnInit() {
    if(typeof(this.folderId) == 'object') {
      this.folderId = this.folderId['ProcessId']
    }

    this.getPublications();
    this.getPublicationDetail();

    window['app-view-publications-page-doRefresh'] = this.doRefresh
  }

  ngOnChanges(changes: any): void {

    if(typeof(this.folderId) == 'object') {
      this.folderId = this.folderId['ProcessId']
    }
    console.log('change view to ',this.folderId)

    setTimeout(()=>{
      this.getPublications();
      this.getPublicationDetail();
    }, 100)


  }

  doRefresh =(event) => {
    this.getPublications();

    setTimeout(() => {
      this.getPublicationDetail();
    }, 3000);
  }

  close() {
    this.closeDesktopComponent.emit();
  }

  getPublicationDetail() {
    this.publications.GetPresidentialAction(this.folderId).subscribe(res=>{
      console.log(res);
      this.item = res;
    });
  }

  getPublications() {
    this.showLoader = true;
    const folderId = this.folderId
    this.publications.GetPublications(folderId).subscribe(res=> {

      this.publicationList = new Array();

      res.forEach(element => {
        let item: Publication = this.publicationPipe.itemList(element)
        this.publicationList.push(item);
      });

      this.publicationListStorage.add(folderId, this.publicationList)

      this.showLoader = false;
    },
    (error)=>{
      if(error.status == '404') {
        this.error = 'Sem publicações disponíveis!';
        this.publicationList= [];
        this.publicationListStorage.add(folderId, this.publicationList)
      }

      this.showLoader = false;

    })

  }

  async AddPublication(publicationType:any, folderId:any) {

    if( window.innerWidth <= 1024) {
      const modal = await this.modalController.create({
        component: NewPublicationPage,
        componentProps:{
          publicationType: publicationType,
          folderId: folderId,
        },
        cssClass: 'new-publication modal modal-desktop',
        backdropDismiss: false
      });
      await modal.present();
      modal.onDidDismiss().then(()=>{
        this.doRefresh(event);
      });
    } else {
      this.addNewPublication.emit({
        publicationType: publicationType,
        folderId: folderId
      })
    }

  }

  async openEditPublication(folderId?:any){
    if( window.innerWidth < 701) {
      const modal = await this.modalController.create({
        component: EditActionPage,
        componentProps: {
          folderId: folderId,
        },
        cssClass: 'new-action modal modal-desktop',
        backdropDismiss: true
      });
      await modal.present();
      modal.onDidDismiss().then(() => {
        //Do nothing
      });
    }
    else{
      this.editPublication.emit(folderId);
    }
  }

  async deletePublication(folderId?:any){
    const loader = this.toastService.loading();
    try {
      await this.publications.DeletePresidentialAction(folderId).toPromise();
      this.toastService._successMessage()
    } catch (e) {
      this.toastService._badRequest()
    }
    finally {
      loader.remove()
    }
  }

  async viewPublicationDetail(publicationId:string) {


    // if( window.innerWidth <= 1024) {
    //   const modal = await this.modalController.create({
    //     component: PublicationDetailPage,
    //     componentProps:{
    //       publicationId: publicationId,
    //     },
    //     cssClass: 'publication-detail modal modal-desktop',
    //     //backdropDismiss: false
    //   });
    //   await modal.present();
    //   modal.onDidDismiss().then(()=>{
    //     this.doRefresh(event);
    //   });
    // } else {
    //   // open publication details
    //   this.openPublicationDetails.emit(publicationId);
    // }

    this.openPublicationDetails.emit(publicationId);

  }

}
