import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { ModalController, Platform } from '@ionic/angular';
import { PublicationFolder } from 'src/app/models/publicationfolder';
import { PublicationsService } from 'src/app/services/publications.service';
import { NewActionPage } from './new-action/new-action.page';
import { ViewPublicationsPage } from './view-publications/view-publications.page';

import { AnimationController } from '@ionic/angular';
import { Publication } from 'src/app/models/publication';
import { ActionsOptionsPage } from 'src/app/shared/popover/actions-options/actions-options.page';
import { EditActionPage } from './edit-action/edit-action.page';
import { ToastService } from 'src/app/services/toast.service';
import { PublicationEventFolderStorage } from 'src/app/store/publication-event-folder.service';
import { PublicationTravelFolderStore } from 'src/app/store/publication-travel-folder.service';
import { SqliteService } from 'src/app/services/sqlite.service';
import { BackgroundService } from 'src/app/services/background.service';
import { ThemeService } from 'src/app/services/theme.service'


@Component({
  selector: 'app-publications',
  templateUrl: './publications.page.html',
  styleUrls: ['./publications.page.scss'],
})
export class PublicationsPage implements OnInit {
  showLoader: boolean;
  publicationFolder: PublicationFolder;
  publication: Publication;

  publicationsEventFolderList: PublicationFolder[];
  actionsListStorage: PublicationFolder[] = new Array();
  publicationsTravelFolderList: PublicationFolder[];

  theDate: any;
  theEndDate: any;
  customDate: any;
  months: string[];
  days: string[];

  publicationEventFolderStorage = PublicationEventFolderStorage
  publicationTravelFolderService = PublicationTravelFolderStore

  desktopComponent: any = {
    showViewPublication: false,
    showAddNewPublication: false,
    showPublicationDetail: false,
    showAddActions: false,
    showEditActions: false
  }

  folderId: string;
  // data set from child component
  publicationType: any;
  publicationId: string;

  // from publication details
  //publication: object;
  hideRefreshBtn = true;
  showSlidingOptions = true;
  idSelected: string;
  skeletonLoader:boolean;

  constructor(
    private router: Router,
    private modalController: ModalController,
    private animationController: AnimationController,
    private publications: PublicationsService,
    private toastService: ToastService,
    private sqliteservice: SqliteService,
    private backgroundservice: BackgroundService,
    private platform: Platform,
    public ThemeService: ThemeService,

  ) {
    this.months = ["Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"];
    this.days = ["Domingo", "Segunda-feira", "Terça-feira", "Quarta-feira", "Quinta-feira", "Sexta-feira", "Sábado"];
    this.skeletonLoader = true;
  }

  ngOnInit() {

    const pathname = window.location.pathname

    this.router.events.forEach((event) => {
      if (event instanceof NavigationEnd && event.url == pathname) {
        this.getActions();
      }
    });
    this.hideRefreshButton();

    this.backgroundservice.registerBackService('Online', () => {
      this.getActions();
    })

  }



  hideRefreshButton() {
    window.onresize = (event) => {
      if (window.innerWidth < 801) {
        this.hideRefreshBtn = false;
        this.showSlidingOptions = false;
      }
      else {
        this.hideRefreshBtn = true;
        this.showSlidingOptions = true;
      }
    }
    if (window.innerWidth < 801) {
      this.hideRefreshBtn = false;
      this.showSlidingOptions = false;
    }
    else {
      this.hideRefreshBtn = true;
      this.showSlidingOptions = true;
    }
  }

  refreshing() {
    setTimeout(() => {
      this.getActions();
    }, 1500);
  }

  doRefresh(event) {
    this.getActions();
    setTimeout(() => {
      event.target.complete();
    }, 250);
  }

  get windowInnerWidth(): number {
    return window.innerWidth
  }

  getDate(date) {
    this.theDate = new Date(date);
    return this.theDate.getDate() + " de " + (this.months[this.theDate.getMonth()]) + " de " + this.theDate.getFullYear()
  }

  getActions() {
    this.showLoader = true;
    this.skeletonLoader = true;
    this.publications.GetPublicationFolderList().subscribe(res => {

      console.log('accoes', res)

      this.publicationsEventFolderList = new Array();
      this.publicationsTravelFolderList = new Array();

      res.forEach(data => {
        let folder: PublicationFolder = {
          ProcessId: data.ProcessId,
          Description: data.Description,
          Detail: data.Detail,
          DateBegin: data.DateBegin,
          DateEnd: data.DateEnd,
          ActionType: data.ActionType,
        }

        this.addActionToDB(folder)

        if (data.ActionType == "Evento") {
          console.log('Evento', folder)
          this.publicationsEventFolderList.push(folder);
        }
        else {
          console.log('Viagem', folder)
          this.publicationsTravelFolderList.push(folder);
        }
        this.showLoader = false;
      });


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

  addActionToDB(folder) {
    if (this.platform.is('desktop') || this.platform.is('mobileweb')) {
    } else {
      this.sqliteservice.addactions(folder);
    }
  }

  getFromDB() {

    if (this.platform.is('desktop') || this.platform.is('mobileweb')) {
    } else {
      this.sqliteservice.getAllActions().then((actions: any[]) => {

        console.log('offline publi', actions)

        this.publicationsEventFolderList = new Array();
        this.publicationsTravelFolderList = new Array();

        actions.forEach(data => {
          let folder: PublicationFolder = {
            ProcessId: data.ProcessId,
            Description: data.Description,
            Detail: data.Detail,
            DateBegin: data.DateBegin,
            DateEnd: data.DateEnd,
            ActionType: data.ActionType,
          }

          if (data.ActionType == "Evento") {
            this.publicationsEventFolderList.push(folder);
          }
          else {
            this.publicationsTravelFolderList.push(folder);
          }
          this.showLoader = false;
        });

      })
    }
  }

  async editAction(folderId?: string) {
    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(() => {
      this.getActions();
    });
    //this.refreshing()
  }

  async deleteAction(id?: string) {
    const loader = this.toastService.loading();
    try {
      await this.publications.DeletePresidentialAction(id).toPromise();
      this.toastService._successMessage()
    } catch (e) {
      this.toastService._badRequest()
    }
    finally {
      loader.remove()
    }
    this.refreshing()
  }

  async AddPublicationFolder(item?: any) {

    this.closeDesktopComponent();
    if (window.innerWidth <= 1024) {

      const modal = await this.modalController.create({
        component: NewActionPage,
        componentProps: {
          item: item,
        },
        cssClass: 'new-action modal modal-desktop',
        backdropDismiss: false
      });
      await modal.present();
      modal.onDidDismiss().then(() => {
        this.getActions();
      });
    } else {
      this.desktopComponent.showAddActions = true;
    }

  }

  goToPublicationsList(folderId: string) {
    if (window.innerWidth <= 800) {
      this.router.navigate(['/home/publications', folderId]);
      this.idSelected = "";
    } else {
      this.closeDesktopComponent();
      this.idSelected = folderId;
      this.folderId = folderId
      this.desktopComponent.showViewPublication = true;
    }

  }

  async viewPublications(folderId: string) {
    this.folderId = folderId

    const enterAnimation = (baseEl: any) => {
      const backdropAnimation = this.animationController.create()
        .addElement(baseEl.querySelector('ion-backdrop')!)
        .fromTo('opacity', '0.01', 'var(--backdrop-opacity)');

      const wrapperAnimation = this.animationController.create()
        .addElement(baseEl.querySelector('.modal-wrapper')!)
        .keyframes([
          { offset: 0, opacity: '0', transform: 'scale(0)' },
          { offset: 1, opacity: '0.99', transform: 'scale(1)' }
        ]);

      return this.animationController.create()
        .addElement(baseEl)
        .easing('ease-out')
        .duration(500)
        .addAnimation([backdropAnimation, wrapperAnimation]);
    }

    const leaveAnimation = (baseEl: any) => {
      return enterAnimation(baseEl).direction('reverse');
    }


    this.closeDesktopComponent();

    // OpenModal
    if (window.innerWidth <= 800) {
      /* let item =  this.publicationFolderList; */
      const modal = await this.modalController.create({
        component: ViewPublicationsPage,
        //enterAnimation,
        //leaveAnimation,
        componentProps: {
          folderId: folderId,
        },
        cssClass: 'new-action modal modal-desktop',
        backdropDismiss: false
      });
      await modal.present();
      modal.onDidDismiss();

    } else {
      // open angular component
      this.folderId = folderId
      this.desktopComponent.showViewPublication = true;
    }

  }

  // called from publications details
  // Emittter
  goBackToViewPublications() {

    this.closeDesktopComponent();
    this.desktopComponent.showViewPublication = true;
  }

  // called from publications details
  // Emitters
  goBackToPubications() {
    this.closeDesktopComponent();
    this.desktopComponent.showViewPublication = true;
  }

  // called from edit publication (Emitters only)
  // Emitters
  async goBacktoPublicationDetails() {
    this.closeDesktopComponent();
    this.desktopComponent.showPublicationDetail = true;

  }

  // add new publication or edit publicaton
  async addNewPublication({ publicationType, folderId, publication }) {

    this.closeDesktopComponent();

    // propr to add new publication
    this.publicationType = publicationType;
    // edit publication will send null
    if (folderId != undefined) {
      this.folderId = folderId;
    }

    this.publication = publication;
    this.desktopComponent.showAddNewPublication = true;
  }

  async editPublication(foolderId:string){
    this.closeDesktopComponent();
    this.desktopComponent.showEditActions = true;
  }

  async openPublicationDetails(publicationId: string) {

    this.publicationId = publicationId;

    this.closeDesktopComponent();
    this.desktopComponent.showPublicationDetail = true;

  }

  async updateDesktopComponent(e?: any) {
    this.getActions();
  }

  async closeDesktopComponent(xx?: any) {

    this.desktopComponent = {
      showViewPublication: false,
      showAddNewPublication: false,
      showPublicationDetail: false,
      showAddActions: false,
      showEditActions: false,
    }
    this.idSelected = "";
  }

  async openOptions(id?: string) {
    this.folderId = id;
    const enterAnimation = (baseEl: any) => {
      const backdropAnimation = this.animationController.create()
        .addElement(baseEl.querySelector('ion-backdrop')!)
        .fromTo('opacity', '0.01', 'var(--backdrop-opacity)');

      const wrapperAnimation = this.animationController.create()
        .addElement(baseEl.querySelector('.modal-wrapper')!)
        .keyframes([
          { offset: 0, opacity: '1', right: '-100%' },
          { offset: 1, opacity: '1', right: '0px' }
        ]);

      return this.animationController.create()
        .addElement(baseEl)
        .easing('ease-out')
        .duration(500)
        .addAnimation([backdropAnimation, wrapperAnimation]);
    }

    const leaveAnimation = (baseEl: any) => {
      return enterAnimation(baseEl).direction('reverse');
    }

    const modal = await this.modalController.create({
      enterAnimation,
      leaveAnimation,
      component: ActionsOptionsPage,
      cssClass: 'model profile-modal search-submodal',
      componentProps: {
        id: id,
      },
      //translucent: true
    });
    await modal.present();
    modal.onDidDismiss().then(res => {
      if (res['data'] == 'edit') {
        this.closeDesktopComponent();
        this.desktopComponent.showEditActions = true;
      } else if (res['data'] == 'delete') {
        setTimeout(() => {
          this.getActions();
        }, 1000)
        this.closeDesktopComponent()
      }
    });
  }

  // this.crop.crop('path/to/image.jpg', {quality: 75})
  // .then(
  //   newImage => console.log('new image path is: ' + newImage),
  //   error => console.error('Error cropping image', error)
  // );

}
