import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { ModalController } from '@ionic/angular';
import { Publication } from 'src/app/models/publication';
import { PublicationFolder } from 'src/app/models/publicationfolder';
import { PublicationPipe } from 'src/app/pipes/publication.pipe';
import { PublicationsService } from 'src/app/services/publications.service';
import { PublicationEventFolderStorage } from 'src/app/store/publication-event-folder.service';
import { PublicationListStorage } from 'src/app/store/publication-list.service';
import { PublicationTravelFolderStore } from 'src/app/store/publication-travel-folder.service';
import { NewPublicationPage } from '../new-publication/new-publication.page';
import { PublicationDetailPage } from './publication-detail/publication-detail.page';
import { SqliteService } from 'src/app/services/sqlite.service';
import { BackgroundService } from 'src/app/services/background.service';
import { ThemeService } from 'src/app/services/theme.service'
import { forkJoin } from 'rxjs';

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

  publicationList: Publication[] = new Array();
  item: PublicationFolder;
  defaultImage = "https://governo.gov.ao/ao/noticias/presidente-joao-lourenco-ouviu-a-voz-da-igreja/"
  folderId: string;
  id: string;
  error: any;

  publicationListStorage = PublicationListStorage
  //
  publicationEventFolderStorage = PublicationEventFolderStorage
  publicationTravelFolderService = PublicationTravelFolderStore

  publicationPipe = new PublicationPipe()
  publicationDitails: any;
  getpublication = [];


  constructor(
    private modalController: ModalController,
    private publications: PublicationsService,
    private activatedRoute: ActivatedRoute,
    private router: Router,
    private sqliteservice: SqliteService,
    private backgroundservice: BackgroundService,
    public ThemeService: ThemeService) {

    this.item = new PublicationFolder();
    this.activatedRoute.paramMap.subscribe(params => {
      console.log(params);

      if (params["params"]) {
        this.folderId = params["params"].folderId;
        // console.log(params["params"]);
      }

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

  ngOnInit() {

    if (typeof (this.folderId) == 'object') {
      this.folderId = this.folderId['ProcessId']
    }
    this.testForkJoin()
    this.getPublicationDetail();
    setTimeout(() => {
      this.getPublicationsIds();
    }, 1000);

    this.backgroundservice.registerBackService('Online', () => {
      this.getPublicationDetail();
      this.testForkJoin()

    })

  }

  ngOnChanges() {

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

    // if (typeof (this.id == 'object') {
    //   this.id = this.id['ProcessId']
    // }
    this.testForkJoin()
    this.getPublicationDetail();
    // this.getPublicationsIds();
  }

  doRefresh = (event) => {
    setTimeout(() => {
      this.testForkJoin()
      this.getPublicationDetail();
      // this.getPublicationsIds();
      event.target.complete();
    }, 3000);

  }

  close() {
    this.modalController.dismiss();
    this.router.navigate(['/home/publications']);
  }

  goBack() {
    this.router.navigate(['/home/publications']);
  }

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

// goes to fork
  // getPublicationsIds() {

  //   this.showLoader = true;
  //   const folderId = this.folderId

  //   this.publications.GetIdsPublicationsImages(this.id).subscribe(res => {

  //     console.log(this.id)

  //     this.publicationList = new Array();

  getPublicationsIds() {

    this.showLoader = true;
    const folderId = this.folderId

    this.publications.GetPublicationsImages(this.folderId).subscribe(res => {

      console.log('publications ids', res)
      this.publicationList = new Array();

       for(let i of res) {
         this.publications.GetPublicationById(i).subscribe(ress => {
           console.log('publications by ids', ress)
           let item: Publication = this.publicationPipe.itemList(ress)
           console.log('publications by ids 2', item)
           this.publicationList.push(item);
         })
       }

      /* res.forEach(element => {
        console.log('publications elements', element)
        this.publications.GetPublicationById(element).subscribe(ress => {
          console.log('publications by ids', ress)
          let item: Publication = this.publicationPipe.itemList(ress)
          console.log('publications by ids 2', item)
          this.publicationList.push(ress);
        })

      }); */

      this.sqliteservice.updateactions(this.folderId, JSON.stringify(this.publicationList));

      this.publicationListStorage.add(folderId, this.publicationList)
      this.getpublication = this.publicationList;

      this.showLoader = false;

      /*  this.publicationList = new Array();

       res.forEach(element => {
         console.log('getPublications', element)
         let item: Publication = this.publicationPipe.itemList(element)
         this.publicationList.push(item);
       });
       this.sqliteservice.updateactions(this.folderId, JSON.stringify(this.publicationList));

       this.publicationListStorage.add(folderId, this.publicationList)
       this.getpublication = this.publicationList; */
    });
  }

  getPublications() {

    this.showLoader = true;
    const folderId = this.folderId

    this.publications.GetPublications(this.folderId).subscribe(res => {

      console.log(this.folderId)

      this.publicationList = new Array();

      res.forEach(element => {
        console.log('getPublications', element)
        let item: Publication = this.publicationPipe.itemList(element)
        this.publicationList.push(item);
        console.log('getPublications 222', item)

      });
      this.sqliteservice.updateactions(this.folderId, JSON.stringify(this.publicationList));

      this.publicationListStorage.add(folderId, this.publicationList)
      this.getpublication = this.publicationList;

      this.showLoader = false;
    }, (error) => {

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

  testForkJoin(){
    forkJoin([
      this.getPublicationsIds(),
      this.getPublications(),


    ]).subscribe(allResults =>{
      this.publicationList = allResults[2]
    })
  }

  getFromDB() {

    this.sqliteservice.getActionById(this.folderId).then((publications) => {
      console.log('publications', publications)
      let item = {
        ActionType: publications[0].ActionType,
        DateBegin: publications[0].DateBegin,
        DateEnd: publications[0].DateEnd,
        Description: publications[0].Description,
        Detail: publications[0].Detail,
        ProcessId: publications[0].ProcessId
      }
      this.publicationDitails = item;

      let publicationArray = [];
      JSON.parse(publications[0].publications).forEach(element => {
        let publicationlis = {
          DateIndex: element.DateIndex,
          DatePublication: element.DatePublication,
          DocumentId: element.DocumentId,
          FileBase64: element.FileBase64,
          FileExtension: element.FileExtension,
          Message: element.Message,
          OrganicEntityId: element.OrganicEntityId,
          OriginalFileName: element.OriginalFileName,
          ProcessId: element.ProcessId
        }
        publicationArray.push(publicationlis);

      });

      this.getpublication = publicationArray;
    })
  }

  async AddPublication(publicationType: any, folderId: any) {
    const modal = await this.modalController.create({
      component: NewPublicationPage,
      componentProps: {
        publicationType: publicationType,
        folderId: this.folderId,
      },
      cssClass: 'new-publication modal modal-desktop',
      backdropDismiss: false
    });
    await modal.present();
    modal.onDidDismiss().then(() => {
      this.doRefresh(event);
    });
  }

  goToPublicationDetail(publicationId: string) {
    this.router.navigate(['/home/publications/view-publications', this.folderId, publicationId]);
  }

  async viewPublicationDetail(publicationId: string) {
    const modal = await this.modalController.create({
      component: PublicationDetailPage,
      componentProps: {
        publicationId: publicationId,
        folderId: this.folderId,
      },
      cssClass: 'publication-detail modal modal-desktop',
      // backdropDismiss: false
    });
    await modal.present();
    modal.onDidDismiss().then(() => {
      this.getPublicationsIds();
    });
  }

}
