import { CalendarEventsComponent } from './calendar-events/calendar-events.component';
import { MatDialog } from '@angular/material/dialog';
import { FormBuilder } from '@angular/forms';
import { MatSnackBar } from '@angular/material/snack-bar';
import { EncService } from './../../../services/enc/enc.service';
import { Router } from '@angular/router';
import { Component, OnInit } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';

interface CalendarDay{
  day: number,
  date: string,
  isActualMonth: boolean,
  isActualDay: boolean,
}
@Component({
  selector: 'app-work-orders',
  templateUrl: './work-orders.component.html',
  styleUrls: ['./work-orders.component.css']
})
export class WorkOrdersComponent implements OnInit {
  MONTHS = ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'];
  
  public btnSmall: boolean = false;
  public txtBuscador:string;
  
  dataSource?: MatTableDataSource<any>;
  selected?: Date | null;

  orderTypes = this._formBuilder.group({
    unica: true,
    periodica: true,
  });

  calendarTitle: string;
  calendarView: string;

  displayedYear: number;
  displayedMonth: number;
  monthDays: Array<Array<CalendarDay>>;

  showLeftPanel: boolean;
  animateClose: boolean;
  animateOpen: boolean;

  constructor(
    private _router: Router,
    private _encService: EncService,
    private _snackBar: MatSnackBar,
    private _formBuilder: FormBuilder,
    private _dialog: MatDialog,
  ) { 
    this.btnSmall = window.innerWidth <= 1405;
    this.txtBuscador = '';
    this.selected = new Date();
    this.calendarTitle = "";
    this.calendarView = "semana";
    this.displayedMonth = 0;
    this.displayedYear = 0;
    this.monthDays = [];

    this.showLeftPanel = true;
    this.animateClose = false;
    this.animateOpen = false;
  }

  ngOnInit(): void {
    let currentDate = new Date();
    let currentMonth = currentDate.getMonth();
    let currentYear = currentDate.getFullYear();

    this.calendarTitle = `${this.MONTHS[currentMonth]} ${currentYear}`;
    this.displayedMonth = currentDate.getMonth();
    this.displayedYear = currentDate.getFullYear();
    this.calcCalendarDays();
  }

  public onResize():void {
    this.btnSmall = window.innerWidth <= 1405;
    if(this.showLeftPanel == false && !this.btnSmall) this.openLeftPanel();
  }

  applyFilter(event: any, type: string){
    let filterValue:string;
    if (type == 'INP') {
      filterValue = (event.target as HTMLInputElement).value;
    }else{
      this.txtBuscador = event;
      filterValue = event;
    }
    this.dataSource!.filter = filterValue.trim().toLowerCase();

    if(this.dataSource?.paginator){
      this.dataSource.paginator.firstPage();
    }
  }

  openSnackBar(msg: string){
    this._snackBar.open (msg, undefined, {
      duration: 2500,
    });
  }

  async openOrder(type: string, idOrder: string | null = null){
    if(type == 'new'){
      this._router.navigate(['sam/GMPR/ORTR/COTP/nuevo']);
    }else if(type == 'edit'){
      console.log(idOrder);
    }else{
      this.openSnackBar('No se encontró la acción solicitada');
    }
  }

  calcCalendarDays(){
    let completeDays: string[] = [];
    let firstDay = new Date(this.displayedYear, this.displayedMonth, 1);
    let lastDay = new Date(this.displayedYear, this.displayedMonth + 1, 0);

    let dayInd = firstDay.getDay();
    let startDays: string[] = [];
    for(let i = dayInd; i > 0; i--){
      let dayNum = i - dayInd;
      let dayObj = new Date(this.displayedYear, this.displayedMonth, dayNum);

      startDays.push(`${dayObj.getDate()}-${dayObj.getMonth()}-${dayObj.getFullYear()}`);
    }

    startDays = startDays.reverse();
    startDays.forEach(day => completeDays.push(day));

    let fdNum = firstDay.getDate();
    let ldNum = lastDay.getDate();
    for(let i = fdNum; i <= ldNum; i++){
      completeDays.push(`${i}-${this.displayedMonth}-${this.displayedYear}`);
    }

    let indLast = lastDay.getDay();
    if(indLast < 6){
      let cont = 1;
      for(let i = indLast; i < 6; i++){
        let dayObj = new Date(this.displayedYear, this.displayedMonth, ldNum + cont);
        completeDays.push(`${dayObj.getDate()}-${dayObj.getMonth()}-${dayObj.getFullYear()}`)
        cont++;
      }
    }

    let rows = completeDays.length / 7;
    let cont = 0;
    let currentDate = new Date();
  
    for(let i = 0; i < rows; i++){
      let rowDays: CalendarDay[] = [];

      for(let j = 0; j < 7; j++){
        let dayArr = completeDays[cont].split('-');
        
        let dayObj: CalendarDay = {
          day: parseInt(dayArr[0]),
          date: completeDays[cont],
          isActualMonth: parseInt(dayArr[1]) == this.displayedMonth && parseInt(dayArr[2]) == this.displayedYear,
          isActualDay: parseInt(dayArr[0]) == currentDate.getDate() && parseInt(dayArr[1]) == currentDate.getMonth() && parseInt(dayArr[2]) == currentDate.getFullYear(),
        };
        
        rowDays.push(dayObj);
        cont++;
      }

      this.monthDays.push(rowDays);
    }
  }

  changeMonth(action: string){
    if(action == 'sub'){
      let newMonth = this.displayedMonth > 0 ? this.displayedMonth - 1 : 11;
      let newYear = this.displayedMonth > 0 ? this.displayedYear : this.displayedYear - 1;

      this.displayedMonth = newMonth;
      this.displayedYear = newYear;
      this.calendarTitle = `${this.MONTHS[newMonth]} ${newYear}`;
    }else if(action == 'add'){
      let newMonth = this.displayedMonth < 11 ? this.displayedMonth + 1 : 0;
      let newYear = this.displayedMonth < 11 ? this.displayedYear : this.displayedYear + 1;

      this.displayedMonth = newMonth;
      this.displayedYear = newYear;
      this.calendarTitle = `${this.MONTHS[newMonth]} ${newYear}`;
    }else if(action == 'today'){
      let currentDate = new Date();
      this.displayedMonth = currentDate.getMonth();
      this.displayedYear = currentDate.getFullYear();
      this.calendarTitle = `${this.MONTHS[this.displayedMonth]} ${this.displayedYear}`;
    }

    this.monthDays = [];
    this.calcCalendarDays();
  }

  checkMonth(event: Date){
    let selectedMonth = event.getMonth();
    let selectedYear = event.getFullYear();

    this.monthDays = [];
    this.calendarTitle = `${this.MONTHS[selectedMonth]} ${selectedYear}`;
    this.displayedMonth = selectedMonth;
    this.displayedYear = selectedYear;
    this.calcCalendarDays();
  }

  closeLeftPanel(){
    this.animateClose = true;
    setTimeout(() => {
      this.showLeftPanel = false;
      this.animateClose = false;
    }, 500);
  }

  openLeftPanel(){
    this.showLeftPanel = true;
    this.animateOpen = true;
    setTimeout(() => this.animateOpen = false, 500);
  }

  openDayEvents(day: CalendarDay){
    this._dialog.open(CalendarEventsComponent);
  }
}
