import { Component, OnInit } from '@angular/core';
import { AbstractControl, FormArray, FormBuilder, FormControl, FormGroup, ValidatorFn, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import * as moment from 'moment';
import { forkJoin, of } from 'rxjs';
import { CommonFunctionService } from 'src/app/core/common/common-function.service';
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';
import { BreakpointsService } from 'src/app/core/services/breakpoints.services';

@Component({
  selector: 'app-allocation-add',
  templateUrl: './allocation-add.component.html',
})
export class AllocationAddComponent implements OnInit {
  Extranet_Hotel_Id;
  Season_List = [];
  AllSeason;
  SelectAllRoom = [];
  ClearAllRoom = [];
  IsMobile;
  AllRoomsData;
  MinDate = new Date();
  position: string;
  displayPosition: boolean;
  Allocation_Form:FormGroup;
  AllDaysArr = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'];
  SelectAllVal = ["Select All"];
  DaysArrValue = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'];
  SelectAll=["Select All"];
  constructor(
    private router: Router,
    public activateRoute:ActivatedRoute,
    private hotelmanageserv:ManageHotelService,
    public apiserv:API,public fb:FormBuilder,public validserv:ValidationService,public commonMasterSer:CommonFunctionService,
    public brkpointsrv:BreakpointsService
  ) { }

  ngOnInit(): void {
    this.Extranet_Hotel_Id = this.activateRoute.snapshot.paramMap.get('Hotel_Eaxtranet_Id') as string;
    this.Allocation_Form = this.fb.group({
      extranet_room_id:this.validserv.required,
      date_type:this.validserv.required,
      AllocationDays:this.fb.array([
        this.fb.group({
          allocation_days:this.validserv.required,
          allocation_type:this.validserv.required
        })
      ])
    });
    this.getAllData();
    this.IsMobile = this.brkpointsrv.IsMobile.getValue();
  }
  ShowDateTypeFields(event){
    this.Season_List = [];
    if(event == 'SPECIFICDATES'){
      this.Allocation_Form.addControl('ContractDatesArr',new FormArray([this.fb.group({
        date:['', Validators.compose([Validators.required, this.dateValidation(new Date())])],
      })]));
      this.Allocation_Form.removeControl('Season_Id');
    }else if(event == 'SEASON'){
      this.Allocation_Form.addControl('Season_Id',new FormControl('',Validators.required))
      this.Allocation_Form.removeControl('ContractDatesArr');
    }else {
      this.Allocation_Form.removeControl('Season_Id');
      this.Allocation_Form.removeControl('ContractDatesArr');
    }
  }
  addDate() {
    let formArray = this.Allocation_Form.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)
        ])]
      }));
   }
  }
  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.Allocation_Form.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();
      }
    }
  }
  showPositionDialog(position) {
    this.position = position;
    this.displayPosition = true;
  };
  backClick(){
    this.hotelmanageserv.Active_tab = 'Allocation';
    this.router.navigateByUrl("Services/Hotel/HotelManage/"+ this.Extranet_Hotel_Id);
  }
  SeasonDataAddRemove(){
    this.Season_List = [];
    let selected_season = this.Allocation_Form.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)
      }
    })
  }
  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)
  }
  CloseCalender(element, index) { 
    let formArray = this.Allocation_Form.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();
      }
    }
  }
  AllocationTypeCheck(ind,event){
    let formgroup = this.Allocation_Form.controls['AllocationDays']['controls'][ind] as FormGroup;
    if(event == 'COUNTSALE'){
      formgroup.addControl('allocation_limit',new FormControl('',Validators.required));
      formgroup.addControl('release_days',new FormControl('',Validators.required));
    }else {
      formgroup.removeControl('allocation_limit');
      formgroup.removeControl('release_days');
    }
  }
  ChangeinWeekDays(i?,event?){
    let selected_days_by_room = [];
    let formdata = this.Allocation_Form.controls['AllocationDays'].value;
    if(event?.includes('Select All')){
      formdata[i].allocation_days.splice(formdata[i].allocation_days.indexOf('Select All'), 1);
      this.DaysArrValue.forEach(days_val=>{
        formdata[i].allocation_days.push(days_val);
      })
      this.Allocation_Form.controls['AllocationDays']['controls'][i]['controls']['allocation_days'].setValue(formdata[i].allocation_days);
    }
    formdata.forEach(e=>{
      if(e.allocation_days && e.allocation_days.length > 0){
        e.allocation_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.Allocation_Form.controls['AllocationDays'] as FormArray;
    formArray.push(this.fb.group({
      allocation_days:this.validserv.required,
      allocation_type:this.validserv.required
    }));
  }
  RemoveAllocation(i){
    let formArray = this.Allocation_Form.controls['AllocationDays'] as FormArray;
    formArray.removeAt(i);
    this.ChangeinWeekDays();
  }
  Save(){
    if (this.Allocation_Form.status == "INVALID") {
      this.validserv.showValidationsMsg(this.Allocation_Form);
      setTimeout(() => {
        this.validserv.scrollToError();
      }, 50);
      return;
    }
    let val = this.Allocation_Form.getRawValue();
    let postObjArr = [];
    val.extranet_room_id.forEach(room_Id=>{
      let PostObj = {
        extranet_room_id:room_Id,
        extranet_hotel_id:this.Extranet_Hotel_Id,
        date_range:'',
        AllocationDays:[]
      };
      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_range'] = 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_range'] = JSON.stringify(date_Arr);
      }
      val.AllocationDays.forEach(allocation_data=>{
        PostObj.AllocationDays.push({
          allocation_days:allocation_data.allocation_days ? allocation_data.allocation_days.join(',') : '',
          allocation_type:allocation_data.allocation_type,
          allocation_limit:allocation_data.allocation_limit ? parseInt(allocation_data.allocation_limit) : 0,
          release_days:allocation_data.release_days ? parseInt(allocation_data.release_days) : 0
        })
      });
      postObjArr.push(PostObj);
    })

    this.apiserv.Post('/ExtranetAllocation/SaveExtranetAllocation',postObjArr).subscribe(resp=>{
      if(resp){
        this.commonMasterSer.showMessage(resp.status,resp.message);
        resp.status ? this.backClick() : '';
      }
    })
  }
  
  SelectAndRemoveAllRoom(){
    const contract_id = this.Allocation_Form.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.Allocation_Form.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.Allocation_Form.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'];
      }
    }
  }
}
