import { Component, OnInit } from '@angular/core';
import { NavigationStart, Router } from '@angular/router';
import { ProcessesService } from 'src/app/services/processes.service';
import { ToastService } from 'src/app/services/toast.service';
import { ExpedienteGdStore } from 'src/app/store/expedientegd-store.service';
import { ExpedienteTaskPipe } from 'src/app/pipes/expediente-task.pipe';
import { SqliteService } from 'src/app/services/sqlite.service';
import { Platform } from '@ionic/angular';
import { BackgroundService } from '../../../services/background.service';
import { ThemeService } from 'src/app/services/theme.service'
import { SortService } from 'src/app/services/functions/sort.service';

@Component({
  selector: 'app-expediente',
  templateUrl: './expediente.page.html',
  styleUrls: ['./expediente.page.scss'],
})
export class ExpedientePage implements OnInit {

  segment: string;
  skeletonLoader = true
  //profile:string;
  showLoader: boolean;

  taskslist = [];
  serialNumber: string;

  //expedienteGdStore = ExpedienteGdStore;
  expedientegbstore = ExpedienteGdStore
  expedienteTaskPipe = new ExpedienteTaskPipe()
  onlinecheck: boolean;

  listToPresent;
  constructor(
    private processes: ProcessesService,
    private router: Router,
    private toastService: ToastService,
    public platform: Platform,
    private sqliteservice: SqliteService,
    private backgroundservice: BackgroundService,
    public ThemeService: ThemeService,
    private sortService: SortService,
  ) { }

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

  LoadList() {

    this.processes.GetTaskListExpediente(false).subscribe(async res => {
      this.skeletonLoader = true
      const result = res

      this.taskslist = new Array();
      let ress = result.filter((data: any) => data.workflowInstanceDataFields.Status == "Active");

      ress.forEach((element: any) => {

        let task = this.expedienteTaskPipe.transform(element)
        this.taskslist.push(task);
        this.addProcessTODb(task);
      });
      this.listToPresent = this.sortService.sortDate(this.taskslist, 'taskStartDate') 
      console.log('expediente list', this.listToPresent)

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

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

  doRefresh(event) {
    this.LoadList();
    setTimeout(() => {
      event.target.complete();
    }, 1000);
  }

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

  goToExpediente(serialNumber: any) {
    //console.log('ABRE');
    this.router.navigate(['/home/gabinete-digital/expediente', serialNumber, 'gabinete-digital']);
  }

  addProcessTODb(task) {
    if (this.platform.is('desktop') || this.platform.is('mobileweb')) {
    } else {
      this.sqliteservice.addProcess(task);
    }
  }

  SqliteAddExpediente(list) {
    list.forEach((expediente) => {
      let data = {
        serialNumber: expediente.serialNumber,
        workflowInstanceFolio: expediente.workflowInstanceFolio,
        Documents: expediente.Documents,
        actions: expediente.actions,
        activityInstanceName: expediente.activityInstanceName,
        formURL: expediente.formURL,
        originator: expediente.originator,
        taskStartDate: expediente.taskStartDate,
        totalDocuments: expediente.totalDocuments,
        workflowDisplayName: expediente.workflowDisplayName,
        workflowID: expediente.workflowID,
        workflowInstanceDataFields: expediente.workflowInstanceDataFields,
        workflowInstanceID: expediente.workflowInstanceID,
        workflowName: expediente.workflowName
      }

      this.sqliteservice.addExpediente(data);
    })

  }

  getEventsFromLocalDb() {

    this.taskslist = new Array();
    this.sqliteservice.getprocessByworkflow("Expediente").then((expediente: any[]) => {
      console.log("All expedientes from local,", expediente)

      expediente.forEach((element) => {

        var workflow = JSON.parse(element.workflowInstanceDataFields);

        let exped = {
          "CreateDate": element.taskStartDate,
          "DocumentsQty": element.totalDocuments,
          "Senders": workflow.Senders,
          "SerialNumber": element.serialNumber,
          "Status": workflow.Status,
          "Subject": workflow.Subject,
          "WorkflowName": element.workflowDisplayName,
          "activityInstanceName": element.activityInstanceName
        }

        this.taskslist.push(exped)

      });

      this.listToPresent = this.taskslist

    })
  }

}
