import { Component, Input, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, NavigationEnd, Router } from '@angular/router';
import { CalendarComponent } from 'ionic2-calendar';
import { removeDuplicate } from 'src/plugin/removeDuplicate.js'
import { customTask } from '../../../models/dailyworktask.model';
import { ProcessesService } from 'src/app/services/processes.service';
import { AlertService } from 'src/app/services/alert.service';
import { PendentesStore } from 'src/app/store/pendestes-store.service';
import { LoginUserRespose } from 'src/app/models/user.model';
import { AuthService } from 'src/app/services/auth.service';
import { CustomTaskPipe } from 'src/app/pipes/custom-task.pipe';

import { SqliteService } from 'src/app/services/sqlite.service';
import { BackgroundService } from 'src/app/services/background.service';
import { Platform } from '@ionic/angular';
import { SortService } from 'src/app/services/functions/sort.service';


@Component({
  selector: 'app-pendentes',
  templateUrl: './pendentes.page.html',
  styleUrls: ['./pendentes.page.scss'],
})
export class PendentesPage implements OnInit {
  @ViewChild(CalendarComponent) myCal: CalendarComponent;

  taskType: string;
  serialNumber: string;
  totalDocs: any;
  showLoader: boolean;
  loggeduser: LoginUserRespose;

  @Input() profile: string;
  segment: string;
  skeletonLoader = true
  pendentesstore = PendentesStore;
  customTaskPipe = new CustomTaskPipe()
  listToPresent = [];

  constructor(
    private processes: ProcessesService,
    private alertService: AlertService,
    private router: Router,
    private authService: AuthService,
    private activatedRoute: ActivatedRoute,
    private sqliteservice: SqliteService,
    private platform: Platform,
    private backgroundservices: BackgroundService,
    private sortService: SortService,
  ) {
    this.loggeduser = authService.ValidatedUser;
    this.profile = 'mdgpr';
  }

  ngOnInit() {
    //Inicializar segment
    this.segment = "despachos";
    const location = window.location
    const pathname = location.pathname + location.search

    this.LoadList()

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

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

  }

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

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

  notImplemented() {
    this.alertService.presentAlert('Funcionalidade em desenvolvimento');
  }

  async LoadList() {

    this.processes.GetPendingTasks(false).subscribe(async res => {
      this.skeletonLoader = true;

      let pendentes = await this.processes.GetPendingTasks(false).toPromise();
      let pendentesList = [];

      pendentes.forEach(element => {
        let task: customTask = this.customTaskPipe.transform(element);
        pendentesList.push(task);
      });

      pendentesList = removeDuplicate(pendentesList)
      pendentesList = this.sortService.sortDate(pendentesList, 'CreateDate');
      this.listToPresent = pendentesList;
      this.skeletonLoader = false;

    }, (error) => {
      if(error.status == 0){
        this.getFromDb();
      }
    })

  }

  getFromDb() {

    this.platform.ready().then(() => {
      this.sqliteservice.getAllProcess().then((process: any[]) => {
        var pendingList = []
        console.log('Pendentes off off',process )
        process.forEach(element => {
          var workflow = JSON.parse(element.workflowInstanceDataFields);
          if (workflow.Status === "Pending") {
            let task = {
              "CreateDate": new Date(element.taskStartDate),
              "DocumentsQty": element.totalDocuments,
              "FolderID": workflow.FolderID,
              "Folio": workflow.Subject,
              "Senders": workflow.Sender,
              "SerialNumber": element.serialNumber,
              "Status": workflow.Status,
              "WorkflowName": element.workflowDisplayName

            }
            pendingList.push(task)
          }
        });

        pendingList = this.sortService.sortDate(pendingList, 'CreateDate');
        this.listToPresent = pendingList;
        console.log('pendentes', pendingList)

      })
    })
  }

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

  doRefresh(event) {
    this.LoadList();

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

  async viewTaskDetails({ SerialNumber, WorkflowName, activityInstanceName }: customTask) {
    if (WorkflowName == 'Despacho') {
      this.router.navigate(['/home/gabinete-digital/despachos', SerialNumber, 'gabinete-digital']);
    }
    else if (WorkflowName == 'Despacho do Presidente da República') {
      this.router.navigate(['/home/gabinete-digital/despachos', SerialNumber, 'gabinete-digital']);
    }
    else if (WorkflowName == 'Pedido de Parecer' || WorkflowName == 'Pedido de Deferimento' || WorkflowName == 'Pedido de Parecer do Presidente') {
      this.router.navigate(['/home/gabinete-digital/pedidos', SerialNumber, 'gabinete-digital']);
    }
    else if (WorkflowName == 'Expediente') {
      this.router.navigate(['/home/gabinete-digital/expediente', SerialNumber, 'gabinete-digital']);
    }
    else if (WorkflowName == 'Expediente' && this.loggeduser.Profile == 'PR') {
      this.router.navigate(['/home/gabinete-digital/expedientes-pr', SerialNumber, 'gabinete-digital']);
    }
    else if (activityInstanceName == "Tarefa de Parecer") {
      this.router.navigate(['/home/gabinete-digital/pedidos', SerialNumber, 'gabinete-digital']);
    }
    else if (activityInstanceName == "Tarefa de Despacho") {
      this.router.navigate(['/home/gabinete-digital/despachos', SerialNumber, 'gabinete-digital']);
    }
    else {
      console.log('cant find page for this task', WorkflowName, activityInstanceName)
    }

  }

  toDateString(e) {
    return new Date(e).toDateString()
  }

}
