import { Component, EventEmitter, Input, OnInit, Output, ViewChild } from '@angular/core';
import { NavigationEnd, NavigationExtras, NavigationStart, Router } from '@angular/router';
import { CalendarComponent } from 'ionic2-calendar';
import { DailyWorkTask } from '../../../models/dailyworktask.model';
import { ProcessesService } from 'src/app/services/processes.service';
import { ModalController } from '@ionic/angular';
import { ExpedienteDetailPage } from 'src/app/pages/gabinete-digital/expediente/expediente-detail/expediente-detail.page';
import { AlertService } from 'src/app/services/alert.service';
import { LoginUserRespose } from 'src/app/models/user.model';
import { AuthService } from 'src/app/services/auth.service';
import { Location } from '@angular/common'
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';
import { RouteService } from 'src/app/services/route.service';

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

  @ViewChild(CalendarComponent) myCal: CalendarComponent;

  taskslist= [];
  serialNumber:string;
  showLoader:boolean;

  loggeduser: LoginUserRespose;
  @Output() openExpedientDetail:EventEmitter<any> = new EventEmitter<any>();

  skeletonLoader = true
  expedienteGdStore = ExpedienteGdStore;
  expedienteTaskPipe = new ExpedienteTaskPipe()

  constructor(
    private processes:ProcessesService,
    private modalController: ModalController,
    private alertService: AlertService,
    private authService: AuthService,
    private router: Router,
    private RouteService: RouteService,
    public ThemeService: ThemeService,
    private sortService: SortService,
    ) {
      this.loggeduser = authService.ValidatedUser;
    }


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

  }

  LoadList() {
    this.skeletonLoader = true

    this.processes.GetTaskListExpediente(false).subscribe(result => {
      console.log(result);
      this.skeletonLoader = false
      this.showLoader =false
      this.taskslist = new Array();
      let res = result.reverse().filter(data => data.workflowInstanceDataFields.Status == "Active");
      res.forEach(element => {
        let task = this.expedienteTaskPipe.transform(element)
        this.taskslist.push(task);
      });
      console.log(this.taskslist);

      this.taskslist = this.sortService.sortDate(this.taskslist, 'CreateDate')
      this.expedienteGdStore.reset(this.taskslist);
      this.skeletonLoader = false
    })
  }

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

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

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

  async viewExpedientDetail(serialNumber:any) {
    const modal = await this.modalController.create({
      component: ExpedienteDetailPage,
      componentProps:{
        enterAnimation: "",
        serialNumber: serialNumber,
        profile: this.loggeduser.Profile,
      },
      cssClass: 'modal modal-desktop',
    });
    await modal.present();
    modal.onDidDismiss().then((res)=>{
      console.log('refresh list');
      this.LoadList();
    });
  }

  goBack() {
    // let navigationExtras: NavigationExtras = {
    //   queryParams: {
    //     "expedientes-pr": true,
    //   }
    // };
    // this.router.navigate(['/home/gabinete-digital'], navigationExtras);

    this.RouteService.goBack();

  }

}
