import { FunctionsService } from './../../../../services/functions.service';
import { PreventiveWorkOrder, PreventiveWorkOrderResponse } from './../../../../interfaces/preventive-work-order.interface';
import { PreventiveMaintenanceService } from './../../../../services/preventive-maintenance.service';
import { lastValueFrom } from 'rxjs';
import { EncService } from './../../../../services/enc/enc.service';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { Component, Inject, OnInit } from '@angular/core';
import { Specialties } from '../../work-orders/calendar-events/calendar-events.component';

@Component({
  selector: 'app-order-viewer',
  templateUrl: './order-viewer.component.html',
  styleUrls: ['./order-viewer.component.css']
})
export class OrderViewerComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;

  idOrder: number;
  workOrder?: PreventiveWorkOrder;

  MONTHS = ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'];
  dayNames = ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'];

  constructor(
    @Inject(MAT_DIALOG_DATA) private data: any,
    private _encService: EncService,
    private _prevMaintService: PreventiveMaintenanceService,
    private _functionsService: FunctionsService,
  ) { 
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";
    this.idOrder = 0;
  }

  ngOnInit(): void {
    this.idOrder = this.data.idOrder;
    this.getWorkOrder();
  }

  async getWorkOrder(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let workOrder: PreventiveWorkOrderResponse = await lastValueFrom(this._prevMaintService.getWorkOrder(`${this.idOrder}`, idUser, 1));

      this.hasError = workOrder.error;
      this.errorStr = workOrder.msg;

      if(!this.hasError){
        this.workOrder = workOrder.response;
      }

      this.isLoading = false;
    }catch(error: any){
      if(error.error == undefined){
        this.errorStr = 'Ocurrió un error inesperado';
      }else if(error.error.msg == undefined){
        this.errorStr = 'Ocurrió un error inesperado';
      }else{
        this.errorStr = error.error.msg;
      }

      this.hasError = true;
      this.isLoading = false;
    }
  }

  orderDate(date: string): string{
    let dateArr = date.split('-');
    dateArr = dateArr.reverse();
    return `${dateArr[0]} de ${this.MONTHS[parseInt(dateArr[1]) - 1]} del ${dateArr[2]}`;
  }

  getRepeat(repeat: string, programDate: string): string{
    let repObj = JSON.parse(repeat);
    let dateArr = programDate.split('-');
    let dateObj = new Date(parseInt(dateArr[0]), parseInt(dateArr[1]) - 1, parseInt(dateArr[2]));
    
    switch(repObj.type){
      case "SE":
        let dayNum = dateObj.getDay();
        let dayStr = '';

        switch(dayNum){
          case 0: dayStr = 'domingos'; break;
          case 1: dayStr = 'lunes'; break;
          case 2: dayStr = 'martes'; break;
          case 3: dayStr = 'miércoles'; break;
          case 4: dayStr = 'jueves'; break;
          case 5: dayStr = 'viernes'; break;
          case 6: dayStr = 'sábados'; break;
        }

        return `Semanalmente los ${dayStr}`;
      break;
      case "TD":
        return "Todos los días a partir de la fecha de inicio.";
      break;
      case "PE":
        return this.customRepeat(repObj.config);
      break;
    }
    console.log(repObj);
    return "";
  }

  customRepeat(value: string): string{
    let resObj = JSON.parse(value);
    let repeatEvery = resObj.repeatEvery.split('|');
    let customRepeat = 'Repetir cada ';

    if(repeatEvery[0] != "1"){
      customRepeat += repeatEvery[0];
    }

    switch(repeatEvery[1]){
      case "0": customRepeat += repeatEvery[0] != "1" ? ' días' : ' día'; break;
      case "1": customRepeat += repeatEvery[0] != "1" ? ' semanas' : ' semana'; break;
      case "2": customRepeat += repeatEvery[0] != "1" ? ' meses' : ' mes'; break;
      case "3": customRepeat += repeatEvery[0] != "1" ? ' años' : ' año'; break;
    }

    let days = 0;
    let daysValues = Object.values(resObj.repeatOn);
    let daysStr = '';
    let cont = 0;
    
    daysValues.forEach(val => {
      if(val){
        daysStr += `${this.dayNames[cont]}, `; 
        days++;
      }

      cont++;
    });

    daysStr = daysStr.substring(0, daysStr.length - 2);
    
    if(days > 1){
      customRepeat += ' los días: ';
    }else{
      customRepeat += ' el día: ';
    }

    customRepeat += daysStr;

    let endsAt = resObj.endsAt.split('|');
    if(endsAt[0] == 'O'){
      let dateArr = endsAt[1].split('-').reverse();
      customRepeat += '. Finaliza el ' + dateArr[0] + ' de ' + this.MONTHS[parseInt(dateArr[1])] + ' del ' + dateArr[2] + '.';
    }else if(endsAt[0] == 'A'){
      let after = endsAt[2];
      customRepeat += '. Finaliza después de ' + after + ' repeti';

      if(after == '1'){
        customRepeat += 'ción.';
      }else{
        customRepeat += 'ciones.';
      }
    }

    return customRepeat.replace('  ', ' ');
  }

  getStartHour(hour: string): string{
    let hourArr = hour.split(':');
    let hourNum = parseInt(hourArr[0]);
    let period = hourNum < 12 ? 'AM' : 'PM';
    
    hourNum = hourNum > 12 ? hourNum - 12 : hourNum;
    let hourStr = `${hourNum}:${hourArr[1]} ${period}`;
    
    return hourStr;
  }

  getPersonal(personal: string): Specialties[]{
    let personalObj: Specialties[] = JSON.parse(personal);
    return personalObj!;
  }

  getPriority(priority: string): string{
    if(priority == '1'){
      return 'Alta';
    }else if(priority == '2'){
      return 'Media';
    }else{
      return 'Baja';
    }
  }

  getDocumentation(documentation: string | null): string[]{
    if(documentation == null){
      return []
    }else{
      console.log(documentation);
    }
    return [];
  }

  getUser(usrReg: string, usrMod: string | null): string{
    if(usrMod == null){
      return usrReg;
    }else{
      return usrMod;
    }
  }

  getDate(dateReg: string, dateMod: string | null): string{
    if(dateMod == null){
      return this._functionsService.orderDate(dateReg)!;
    }else{
      return this._functionsService.orderDate(dateMod)!;
    }
  }
}
