import { Component, OnInit} from '@angular/core';
import { customTask} from '../../../models/dailyworktask.model';
import { ProcessesService } from 'src/app/services/processes.service';
import { AuthService } from 'src/app/services/auth.service';
import { LoginUserRespose } from 'src/app/models/user.model';
import { NavigationStart, Router } from '@angular/router';
import { DespachosprStore } from 'src/app/store/despachospr-store.service';
import { CustomTaskPipe } from 'src/app/pipes/custom-task.pipe';
import { SortService } from 'src/app/services/functions/sort.service';

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

  customTaskPipe = new CustomTaskPipe()
  skeletonLoader = true

  loggeduser: LoginUserRespose;
  despachosprstore = DespachosprStore;

constructor (
  private processes:ProcessesService,
  private authService: AuthService,
  private router: Router,
  private sortService: SortService,

  ) {
    this.loggeduser = authService.ValidatedUser;
  }

  ngOnInit() {

    this.LoadList()

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

  }

  async LoadList() {

    this.skeletonLoader = true;

    let result = await this.processes.GetTasksList("Despacho do Presidente da República", false).toPromise();
    let despachoList = [];

    let despachosPr;
    switch (this.loggeduser.Profile) {
      case 'MDGPR':
        despachosPr = result.reverse().filter(data => data.activityInstanceName == "Tarefa de Despacho");
        break;
      case 'PR':
        despachosPr = result.reverse().filter(data => data.activityInstanceName == "Concluir Despacho");
        break;
    }

    despachosPr = despachosPr.filter(data => data.workflowInstanceDataFields.Status == "Active");

    despachosPr.forEach( (element, index) => {

      let task: customTask = this.customTaskPipe.transform(element);

      despachoList.push(task);
    });

    despachoList = this.sortService.sortDate(despachoList, 'CreateDate')
    this.despachosprstore.reset(despachoList);
    this.skeletonLoader = false;

  }


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

  doRefresh() {

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

  goToDespacho({ SerialNumber } :customTask) {
    this.router.navigate(['/home/gabinete-digital/despachos-pr',SerialNumber,'gabinete-digital']);
  }

}
