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';

@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
  expedienteTaskPipe = new ExpedienteTaskPipe()
  
  constructor(
    private processes:ProcessesService,
    private router: Router,
    private toastService: ToastService
  ) {}

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

  async LoadList() {
    this.skeletonLoader = true

    try {
      const expediente: object[] = await this.processes.GetTaskListExpediente(false).toPromise()
      const result = expediente
      
      this.taskslist = new Array();
      let res = result.reverse().filter((data: any) => data.workflowInstanceDataFields.Status == "Active");

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

        let task =  this.expedienteTaskPipe.transform(element)
        this.taskslist.push(task);
      });
      
      this.expedienteGdStore.reset(this.taskslist);

    } catch (error) {
      this.toastService.badRequest('Processo não encontrado')
      this.goBack()
    } finally {
      this.skeletonLoader = false;
    }

  }

  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']);
  }

}
