import { Component, OnInit } from '@angular/core';
import { NavigationStart, Router } from '@angular/router';
import { DespachoService } from 'src/app/Rules/despacho.service';
import { DespachoStore } from 'src/app/store/despacho-store.service';

@Component({
  selector: 'app-despachos',
  templateUrl: './despachos.page.html',
  styleUrls: ['./despachos.page.scss'],
})

export class DespachosPage implements OnInit {

  despachoStore = DespachoStore;

  constructor (
    private router: Router,
    private despachoRule: DespachoService
  ) {
      
    }

  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 refreshing() {
    setTimeout(() => {
      this.LoadList();
    }, 1000);
  }

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

  async LoadList() {

    await this.despachoRule.getList({updateStore: true})
  }

  get skeletonLoader(): boolean {
    return this.despachoRule.LoaderService.loading
  }

  doRefresh(event) {
    this.LoadList();

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

  async GoToDespacho(serialNumber:any) {
    console.log('Despachos serial',serialNumber)
    this.router.navigate(['/home/gabinete-digital/despachos',serialNumber,'gabinete-digital']);
  }


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

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

}
