import { Component, OnInit } from '@angular/core';
import { AbstractControl, FormArray, FormBuilder, FormGroup, ValidatorFn, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import * as moment from 'moment';
import { MessageService } from 'primeng/api';
import { ValidationService } from 'src/app/core/common/validation.service';
import { ManageHotelService } from 'src/app/core/services/HotelServices/manage-hotel.service';
import { API } from 'src/app/core/services/api.service';

@Component({
  selector: 'app-hotel-season-add',
  templateUrl: './hotel-season-add.component.html',
})
export class HotelSeasonAddComponent implements OnInit {

  constructor(public activateRoute:ActivatedRoute,public fb:FormBuilder,public validserv:ValidationService,public apiserv:API,public MsgService:MessageService,private router: Router ,
    private hotelmanageserv:ManageHotelService) { }
  Hotel_Season_Form:FormGroup;
  MinDate = new Date();
  Extranet_Hotel_Id;
  Edit_Id;

  ngOnInit(): void {  
    this.Extranet_Hotel_Id = this.activateRoute.snapshot.paramMap.get('Hotel_Eaxtranet_Id') as string;
    this.Edit_Id = this.activateRoute.snapshot.paramMap.get('RuleId') as string;
    this.Hotel_Season_Form = this.fb.group({
      extranet_season_id:'',
      extranet_hotel_id:this.Extranet_Hotel_Id,
      season_name:this.validserv.required,
      ExtranetSeasonDetail:this.fb.array([
        this.fb.group({
          extranet_season_detail_id:'',
          date:['', Validators.compose([
            Validators.required,
            this.dateValidation(new Date(new Date().setDate(new Date().getDate() - 1)))
          ])]
        })
      ])
    })
    if(this.Edit_Id){
      this.apiserv.Get('/ExtranetSeason/GetExtranetSeasonById/'+this.Edit_Id).subscribe(res=>{
        if(res && res.status){
          this.setvalue(res.data)
        }
      })
    }
  }
  CloseCalender(element, index) { 
    let formArray = this.Hotel_Season_Form.controls['ExtranetSeasonDetail']['controls'];
    if (element.value[0] && element.value[1]) {
      element.overlayVisible = false;
      element.datepickerClick = true;
      if (formArray.length >= (index + 2)) {
        formArray[index + 1].get("date").clearValidators();
        formArray[index + 1].get("date").setErrors(null);
        formArray[index + 1].get("date").addValidators([this.dateValidation(element.value[1])]);
        formArray[index + 1].get("date").markAsTouched();
        formArray[index + 1].get("date").updateValueAndValidity();
        formArray[index + 1].get("date").markAsTouched();
      }
    }
  }
  addDate() {
    let formArray = this.Hotel_Season_Form.controls['ExtranetSeasonDetail'] as FormArray;
    let date = new Date();
    let currentDate = date;
    currentDate = new Date(currentDate.getTime() - 1 * 24 * 60 * 60 * 1000);
    if(formArray.length > 0){
    if (formArray.length > 0) {
      let formdate = formArray.controls[formArray.length - 1].get('date').value;
      if (formdate && formdate.length == 2) {
        currentDate = formdate[1];
      }
    }
      formArray.push(this.fb.group({
        extranet_season_detail_id:'',
        date: ['', Validators.compose([
          Validators.required,
          this.dateValidation(currentDate)
        ])]
      }));
   }
  }
  public dateValidation(toDate): ValidatorFn {
    return (control: AbstractControl): { [key: string]: boolean } | null => {
      if (control.value) {
        if (control.value.length <= 1 || control.value[1] == null) {
          return { 'todate': true };
        }
        if (toDate && control.value.length <= 1 || control.value[0] <= toDate) {
          return { 'range': true };
        }
      }
      return null;
    };
  }
  removeDate(index) {
    let formArray = this.Hotel_Season_Form.controls['ExtranetSeasonDetail'] as FormArray;
    formArray.removeAt(index);
    let date = new Date();
    let currentDate = date;
    currentDate = new Date(currentDate.getTime() - 1 * 24 * 60 * 60 * 1000);
    if (formArray.length > 0) {
      if(index > 0){
        let formdate = formArray.controls[index - 1].get('date').value;
        if (formdate && formdate.length == 2) {
          currentDate = formdate[1];
        }
      }
      if (formArray.controls.length >= (index + 1)) {
        formArray.controls[index].get("date").clearValidators();
        formArray.controls[index].get("date").setErrors(null);
        formArray.controls[index].get("date").addValidators([this.dateValidation(currentDate)]);
        formArray.controls[index].get("date").markAsTouched();
        formArray.controls[index].get("date").updateValueAndValidity();
      }
    }
  }
  Save(){
    if (this.Hotel_Season_Form.status == "INVALID") {
      this.validserv.showValidationsMsg(this.Hotel_Season_Form);
      setTimeout(() => {
        this.validserv.scrollToError();
      }, 50);
      return;
    }
    let val = this.Hotel_Season_Form.getRawValue();
    let ExtranetSeasonDetailArr = [];
    val.ExtranetSeasonDetail.forEach(data=>{
      let from_date = new Date(Date.UTC(data.date[0].getFullYear(), data.date[0].getMonth(), data.date[0].getDate()))
      let to_date = new Date(Date.UTC(data.date[1].getFullYear(), data.date[1].getMonth(), data.date[1].getDate()))
      let dateObj={
        extranet_season_detail_id:data.extranet_season_detail_id ? data.extranet_season_detail_id : '',
        from_date: moment(from_date).toISOString(),
        to_date: moment(to_date).toISOString()
      }
      ExtranetSeasonDetailArr.push(dateObj)
    })
   
    let reqObj = {
      extranet_season_id:val.extranet_season_id,
      extranet_hotel_id:this.Extranet_Hotel_Id,
      season_name:val.season_name,
      ExtranetSeasonDetail:ExtranetSeasonDetailArr
    }
    this.apiserv.Post('/ExtranetSeason/SaveExtranetSeason',reqObj).subscribe(data=>{
      if(data){
        this.MsgService.add({
          severity: data.status ? "success" : "error",
          detail: data.message,
        });
        data.status ? this.backbutton() : '';
      }
    })
  }
  backbutton(){
    this.hotelmanageserv.Active_tab = 'Season';
    this.router.navigateByUrl("Services/Hotel/HotelManage/"+ this.Extranet_Hotel_Id);
  }
  setvalue(Resp){
    this.Hotel_Season_Form.get('season_name').setValue(Resp?.ExtranetSeason.season_name);
    this.Hotel_Season_Form.get('extranet_season_id').setValue(Resp?.ExtranetSeason.extranet_season_id);
    if(Resp.ExtranetSeasonDetail && Resp.ExtranetSeasonDetail.length > 0){
      Resp.ExtranetSeasonDetail.forEach((Season_detail,dateIndex)=>{
        dateIndex > 0 ? this.addDate() : "";
        let firstdate = new Date(Season_detail.from_date);
        let lastdate = new Date(Season_detail.to_date );
        this.Hotel_Season_Form.controls['ExtranetSeasonDetail']['controls'][dateIndex].get("date").setValue([firstdate, lastdate]);
        this.Hotel_Season_Form.controls['ExtranetSeasonDetail']['controls'][dateIndex].get("extranet_season_detail_id").setValue(Season_detail.extranet_season_detail_id);
      })
    }
  }
}
