import { Component, Inject, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { ResourcesService } from '../../../../services/resources.service';

@Component({
    selector: 'app-custom-repeat',
    templateUrl: './custom-repeat.component.html',
    styleUrl: './custom-repeat.component.css',
    standalone: false
})
export class CustomRepeatComponent implements OnInit {
  repeatOptions = ['Día', 'Semana', 'Mes', 'Año'];
  frecuency = new FormControl(1);
  period = new FormControl(1);
  endDate = new FormControl({value: new Date(), disabled: true});
  repetitions = new FormControl({value: 1, disabled: true});
  days = {sun: false, mon: false, tue: false, wed: false, thu: false, fri: false, sat: false};
  endsAt = 'N';
  minDate = new Date();

  constructor(
    @Inject(MAT_DIALOG_DATA) private _data: any,
    private _dialogRef: MatDialogRef<CustomRepeatComponent>,
    private _resourcesService: ResourcesService,
  ) { }

  ngOnInit(): void {
    let day = this._data.date.getDay();
    switch(day){
      case 0: this.days.sun = true; break;
      case 1: this.days.mon = true; break;
      case 2: this.days.tue = true; break;
      case 3: this.days.wed = true; break;
      case 4: this.days.thu = true; break;
      case 5: this.days.fri = true; break;
      case 6: this.days.sat = true; break;
    }

    this.minDate = this._data.date;
    this.endDate.setValue(this.minDate);
    this.frecuency.valueChanges.subscribe(val => {
      if(val! < 1){
        this.frecuency.setValue(1);
      }

      this.repeatOptions.forEach(item => {
        if(val! > 1){
          this.repeatOptions = ['Días', 'Semanas', 'Meses', 'Años'];
        }else{
          this.repeatOptions = ['Día', 'Semana', 'Mes', 'Año'];
        }
      });
    });

    this.repetitions.valueChanges.subscribe(val => {
      if(val! < 1){
        this.repetitions.setValue(1);
      }
    });

    if(this._data.repeat != null){
      this.setConfig(this._data.repeat);
    }
  }

  setConfig(configStr: string){
    let configObj = JSON.parse(configStr);
    let repeatEvery = configObj.repeatEvery.split("|");
    let endsAt = configObj.endsAt.split("|");

    this.frecuency.setValue(parseInt(repeatEvery[0]));
    this.period.setValue(parseInt(repeatEvery[1]));

    this.days = configObj.repeatOn;
    this.endsAt = endsAt[0];

    if(endsAt[0] == 'A'){
      this.repetitions.setValue(parseInt(endsAt[2]));
      this.repetitions.enable();
    }else if(endsAt[0] == 'O'){
      let dateArr = endsAt[1].split('-');
      let dateObj = new Date(parseInt(dateArr[0]), parseInt(dateArr[1]), parseInt(dateArr[2]));

      this.endDate.setValue(dateObj);
      this.endDate.enable();
    }
  }

  endChange(event: any){
    let val = event.value;
    
    if(val == 'O'){
      this.endDate.enable();
      this.repetitions.disable();
    }else if(val == 'A'){
      this.endDate.disable();
      this.repetitions.enable();
    }else if(val == 'N'){
      this.endDate.disable();
      this.repetitions.disable();
    }
  }

  save(){
    let hasAtLeastOneDay = false;
    let daysValues = Object.values(this.days);

    daysValues.forEach(item => {
      if(item){
        hasAtLeastOneDay = true;
      }
    });

    if(!hasAtLeastOneDay){
      this._resourcesService.openSnackBar('Debe seleccionar al menos un día de repetición');
    }else{
      let responseObj = {
        repeatEvery: `${this.frecuency.value}|${this.period.value}`,
        repeatOn: this.days,
        endsAt: `${this.endsAt}|${`${this.endDate.value?.getFullYear()}-${this.endDate.value?.getMonth()}-${this.endDate.value?.getDate()}`}|${this.repetitions.value}`,
      };

      this._dialogRef.close(JSON.stringify(responseObj));
    }
  }
}
