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


@Component({
  selector: 'app-minimum-stay-add',
  templateUrl: './minimum-stay-add.component.html',
})
export class MinimumStayAddComponent implements OnInit{

  Extranet_Hotel_Id;
  Edit_Id;
  IsMobile;
  SelectAllRoom = [];
  ClearAllRoom = [];
  AllRoomsData;
  displayPosition: boolean;
  position: string;
  Season_List = [];
  AllSeason;
  MinDate = new Date();
  MinStayForm: FormGroup;
  AllDaysArr = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'];
  SelectAllVal = ["Select All"];
  DaysArrValue = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'];
  SelectAll=["Select All"];
  
  constructor(
    public activateRoute:ActivatedRoute,
    private router:Router,
    private hotelmanageserv:ManageHotelService,
    private fb:FormBuilder,
    public validserv:ValidationService,
    private apiserv:API,
    public brkpointsrv:BreakpointsService,
    private commonMasterSer:CommonFunctionService
  )  {}

  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.InitForm();
    this.getAllData();
    this.IsMobile = this.brkpointsrv.IsMobile.getValue();

  }

  showPositionDialog(position) {
    this.position = position;
    this.displayPosition = true;
  };

  InitForm(){
    this.MinStayForm = this.fb.group({
      extranet_room_min_stay_id: '',
      extranet_room_id: this.validserv.required,
      date_type:this.validserv.required,
      ApplicableDays:this.fb.array([
        this.fb.group({
          applicable_days:this.validserv.required,
          min_stay:this.validserv.required,
          extranet_room_min_stay_id:''
        })
      ])
    })
  }

  getAllData(){
    forkJoin(
      this.GetAllRooms(),
      this.GetAllSeason()
    ).subscribe(res=>{
      if(res && res.length > 0){
        this.AllRoomsData = res[0] ? res[0].data : [];
        if(res[0].data){
          this.SelectAllRoom = ['Select All'];
        }
        this.AllSeason = res[1].data ? res[1].data : [];
      }
    });
  }
  GetAllRooms(){
    let ReqObj = {
      extranet_hotel_id : this.Extranet_Hotel_Id,
      extranet_room_id : '',
      room_name : '',
      room_view_name : '',
    }
    return this.apiserv.Post('/ExtranetRoomContract/GetAllExtranetHotelRoomName',ReqObj)
  }
  GetAllSeason(){
    let ReqObj = {
      season_name:'',
      hotel_id:this.Extranet_Hotel_Id
    }
    return this.apiserv.Post('/ExtranetSeason/GetAllExtranetSeason',ReqObj)
  }

  SeasonDataAddRemove(){
    this.Season_List = [];
    let selected_season = this.MinStayForm.controls['Season_Id'].value;
    selected_season.forEach(data=>{
      let matched_season_by_id = this.AllSeason.find(e=>e.extranet_season_id == data);
      if(matched_season_by_id){
        if(typeof(matched_season_by_id['date_range']) == 'string'){
          matched_season_by_id['date_range'] = matched_season_by_id.date_range.split(', ');
          matched_season_by_id['date_range'].forEach((z,i)=>{
            matched_season_by_id['date_range'][i] =  moment(z.split(' - ')[0]).format('DD MMM YYYY') + ' to ' + moment(z.split(' - ')[1]).format('DD MMM YYYY')
          })
        }
        this.Season_List.push(matched_season_by_id);
        console.log(this.Season_List)
      }
    })
  }
  
  backClick(){
    this.hotelmanageserv.Active_tab = 'MinimumStay';
    this.router.navigateByUrl("/Services/Hotel/HotelManage/" + this.Extranet_Hotel_Id);
  }
  ShowDateTypeFields(event){
    this.Season_List = [];
    if(event == 'SPECIFICDATES'){
      this.MinStayForm.addControl('ContractDatesArr',new FormArray([this.fb.group({
        date:['', Validators.compose([Validators.required, this.dateValidation(new Date())])],
      })]));
      this.MinStayForm.removeControl('Season_Id');
    }else if(event == 'SEASON'){
      this.MinStayForm.addControl('Season_Id',new FormControl('',Validators.required))
      this.MinStayForm.removeControl('ContractDatesArr');
    }else {
      this.MinStayForm.removeControl('Season_Id');
      this.MinStayForm.removeControl('ContractDatesArr');
    }
  }
  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.MinStayForm.controls['ContractDatesArr'] 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([Validators.required,this.dateValidation(currentDate)]);
        // formArray.controls[index].get("date").markAsTouched();
        formArray.controls[index].get("date").updateValueAndValidity();
        // formArray.controls[index].get("date").markAsTouched();
      }
    }
  }
  addDate() {
    let formArray = this.MinStayForm.controls['ContractDatesArr'] 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)
        ])]
      }));
   }
  }
  CloseCalender(element, index) { 
    let formArray = this.MinStayForm.controls['ContractDatesArr']['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([Validators.required,this.dateValidation(element.value[1])]);
        formArray[index + 1].get("date").markAsTouched();
        formArray[index + 1].get("date").updateValueAndValidity();
        formArray[index + 1].get("date").markAsTouched();
      }
    }
  }
  ChangeinWeekDays(i?,event?){
    let selected_days_by_room = [];
    let formdata = this.MinStayForm.controls['ApplicableDays'].value;
    if(event?.includes('Select All')){
      formdata[i].applicable_days.splice(formdata[i].applicable_days.indexOf('Select All'), 1);
      this.DaysArrValue.forEach(days_val=>{
        formdata[i].applicable_days.push(days_val);
      })
      this.MinStayForm.controls['ApplicableDays']['controls'][i]['controls']['applicable_days'].setValue(formdata[i].applicable_days);
    }
    formdata.forEach(e=>{
      if(e.applicable_days && e.applicable_days.length > 0){
        e.applicable_days.forEach(days=>{
          selected_days_by_room.push(days);
        })
      }
    })
    this.DaysArrValue =  this.AllDaysArr.filter(item => !selected_days_by_room.includes(item));
    if(this.DaysArrValue.length == 0){
      this.SelectAllVal = []
    }else {
      this.SelectAllVal = this.SelectAll;
    }
  }

  AddAllocationDays(){
    let formArray = this.MinStayForm.controls['ApplicableDays'] as FormArray;
    formArray.push(this.fb.group({
      applicable_days:this.validserv.required,
      min_stay:this.validserv.required,
      extranet_room_min_stay_id:''
    }));
  }
  RemoveAllocation(i){
    let formArray = this.MinStayForm.controls['ApplicableDays'] as FormArray;
    formArray.removeAt(i);
    this.ChangeinWeekDays();
  }
  Save(){
    if (this.MinStayForm.status == "VALID") {
      let val = this.MinStayForm.getRawValue();
      let PostObj = {
        extranet_room_id:val.extranet_room_id ? val.extranet_room_id.join(',') : '',
        extranet_hotel_id:this.Extranet_Hotel_Id,
        date_ranges:'',
        extranet_room_min_stay:[]
      };
      if(val.date_type == 'SPECIFICDATES'){
        let date_Arr = [];
        val.ContractDatesArr.forEach(data=>{
          date_Arr.push({
            date_from: moment(data.date[0]).format('YYYY-MM-DD'),
            date_to: moment(data.date[1]).format('YYYY-MM-DD'),
          })
        });
        PostObj['date_ranges'] = JSON.stringify(date_Arr);
      }
      if(val.date_type == 'SEASON'){
        let date_Arr = [];
        this.Season_List.forEach(data=>{
          data.date_range.forEach(season_date=>{
            date_Arr.push({
              date_from: moment(season_date.split(' to ')[0]).format('YYYY-MM-DD'),
              date_to: moment(season_date.split(' to ')[1]).format('YYYY-MM-DD'),
            })
          })
        });
        PostObj['date_ranges'] = JSON.stringify(date_Arr);
      }
      val.ApplicableDays.forEach(allocation_data=>{
        PostObj.extranet_room_min_stay.push({
          applicable_days:allocation_data.applicable_days ? allocation_data.applicable_days.join(',') : '',
          min_stay:allocation_data.min_stay ? allocation_data.min_stay : "",
          extranet_room_min_stay_id:allocation_data.extranet_room_min_stay_id ? allocation_data.extranet_room_min_stay_id : '',
        })
      });

    this.apiserv.Post('/ExtranetMinStay/SaveExtranetMinStay',PostObj).subscribe(resp=>{
      if(resp){
        this.commonMasterSer.showMessage(resp.status,resp.message);
        resp.status ? this.backClick() : '';
      }
    })
    }else {
      this.validserv.showValidationsMsg(this.MinStayForm);
      setTimeout(() => {
        this.validserv.scrollToError();
      }, 50);
    }
  }

  SelectAndRemoveAllRoom(){
    const contract_id = this.MinStayForm.get('extranet_room_id').value
    if (contract_id && contract_id.length > 0 && (contract_id.includes('Select All') || contract_id.length == this.AllRoomsData.length) && !contract_id.includes('Clear All')) {
      let room_id_List = []
      this.AllRoomsData.forEach(d=>{
        room_id_List.push(d.extranet_room_id)
      });
      this.MinStayForm.get('extranet_room_id').setValue(room_id_List);
      this.SelectAllRoom = [];
      this.ClearAllRoom = ['Clear All'];
    } else if (contract_id && contract_id.length > 0 && (contract_id.includes('Clear All'))){
      this.MinStayForm.get('extranet_room_id').setValue([]);
      this.SelectAllRoom = ['Select All'];
      this.ClearAllRoom = [];
    } else {
      this.SelectAllRoom = ['Select All'];
      if(contract_id?.length > 0){
        this.ClearAllRoom = ['Clear All'];
      }
    }
  }
}
