import { Component, OnInit } from '@angular/core';
import { NavigationStart, Router } from '@angular/router';
import { DespachoService } from 'src/app/Rules/despacho.service';
import { DespachoStore } from 'src/app/store/despacho-store.service';

import { SqliteService } from 'src/app/services/sqlite.service';
import { Platform } from '@ionic/angular';
import { isThisHour } from 'date-fns';
import { BackgroundService } from 'src/app/services/background.service';
import { ThemeService } from 'src/app/services/theme.service'


@Component({
  selector: 'app-despachos',
  templateUrl: './despachos.page.html',
  styleUrls: ['./despachos.page.scss'],
})

export class DespachosPage implements OnInit {

  despachoStore = DespachoStore;
  listToPresent = [];

  constructor(
    private router: Router,
    private despachoRule: DespachoService,
    private sqliteservice: SqliteService,
    private platform: Platform,
    private backgroundservice: BackgroundService,
    public ThemeService: ThemeService
  ) {

  }

  ngOnInit() {

    const location = window.location
    const pathname = location.pathname + location.search

    this.LoadList()

    this.router.events.forEach((event) => {
      if (event instanceof NavigationStart && event.url.startsWith(pathname)) {
        if (window.location.pathname.split('/').length >= 4 && window.location.pathname.startsWith('/home/gabinete-digital')) {
          this.refreshing()
        } else {
          this.LoadList()
        }
      }
    });

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

  }

  async refreshing() {
    setTimeout(() => {
      this.LoadList();
    }, 1000);
  }

  segmentChanged(ev: any) {
    this.LoadList();
  }

  async LoadList() {

    await this.despachoRule.getList({ updateStore: true }).then((pre) => {
      this.listToPresent = pre;
      console.log('despachooo', pre)
    }).catch(() => {
      this.getFromDb()
    })

  }

  getFromDb() {

    this.platform.ready().then(() => {
      if (this.platform.is('desktop') || this.platform.is('mobileweb')) {
      } else {
        this.sqliteservice.getprocessByworkflow('Despacho').then((process: any[]) => {
          var listtopresent = [];
          process.forEach(element => {
            var workflow = JSON.parse(element.workflowInstanceDataFields);
            let task = {
              "CreateDate": element.taskStartDate,
              "DocId": workflow.DispatchDocID,
              "DocumentURL": undefined,
              "DocumentsQty": element.totalDocuments,
              "FolderID": workflow.FolderID,
              "Folio": workflow.Subject,
              "Remetente": undefined,
              "Senders": workflow.Sender,
              "SerialNumber": element.serialNumber,
              "Status": workflow.Status,
              "WorkflowName": element.workflowDisplayName
            }

            listtopresent.push(task);

          });

          this.listToPresent = listtopresent;
          console.log('Tarefas de despach', this.listToPresent)

        })
      }
    })
  }

  get skeletonLoader(): boolean {
    return this.despachoRule.LoaderService.loading
  }

  doRefresh(event) {
    this.LoadList();

    setTimeout(() => {
      event.target.complete();
    }, 2000);
  }

  async GoToDespacho(serialNumber: any) {
    this.router.navigate(['/home/gabinete-digital/despachos', serialNumber, 'gabinete-digital']);
  }


  goBack() {
    this.router.navigate(['/home/gabinete-digital']);
  }

  goToList() {
    this.router.navigate(['/home/gabinete-digital/despachos']);
  }

}
