import { Component, Input, OnInit } from '@angular/core';
import { NavigationStart, Router } from '@angular/router';
import { ProcessesService } from 'src/app/services/processes.service';
import { AlertService } from 'src/app/services/alert.service';
import { ExpedienteGdStore } from 'src/app/store/expedientegd-store.service';
import { ExpedienteTaskPipe } from 'src/app/pipes/expediente-task.pipe';
import { ThemeService } from 'src/app/services/theme.service'
import { SortService } from 'src/app/services/functions/sort.service';

@Component({
  selector: 'app-expedients',
  templateUrl: './expedients.page.html',
  styleUrls: ['./expedients.page.scss'],
})
export class ExpedientsPage implements OnInit {
  segment:string;

  taskslist = [];
  serialNumber:string;

  @Input() profile:string;
  skeletonLoader = true
  expedientegbstore = ExpedienteGdStore

  expedienteTaskPipe = new ExpedienteTaskPipe()

  constructor(
    private processes:ProcessesService,
    private alertService: AlertService,
    private router: Router,
    public ThemeService: ThemeService,
    private sortService: SortService,
    ) {
      this.profile = 'mdgpr';

    }

  ngOnInit() {
    //Inicializar segment
    this.segment = "expedientes";
    this.LoadList()

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

  }

  segmentChanged() {
    this.LoadList();
  }

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

  LoadList() {

    this.skeletonLoader = true

    this.processes.GetTaskListExpediente(false).subscribe(result => {
      this.taskslist = [];
      this.skeletonLoader = false

      let res = result.filter(data => data.workflowInstanceDataFields.Status == "Active");
      res.forEach(element => {
        let task = this.expedienteTaskPipe.transform(element)
        this.taskslist.push(task);

      });

      this.taskslist = this.sortService.sortDate(this.taskslist, 'CreateDate')
      this.expedientegbstore.reset(this.taskslist);
    });
  }

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

  }

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

}
