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 { API } from 'src/app/core/services/api.service';
import { ManageHotelService } from 'src/app/core/services/HotelServices/manage-hotel.service';


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

  Extranet_Hotel_Id;
  constructor(public activateRoute:ActivatedRoute,private router:Router,private hotelmanageserv:ManageHotelService,
    public apiserv:API,public fb:FormBuilder,public validserv:ValidationService,public commonMasterSer:CommonFunctionService) { }
    ddLoader;
    timer;
    MealPlan;
    CurrencyList;
    Edit_Id;
    occupancy_Limit_Child = [0,1,2,3,4,5,6,7,8,9,10,11];
    MealAddForm:FormGroup;
  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.GetAllMeal();
    this.GetMealAddOnById();
  }
  initForm(){
    this.MealAddForm = this.fb.group({
      extranet_meal_addon_id:'',
      extranet_meal_plan_id:this.validserv.required,
      addon_name:this.validserv.required,
      currency:this.validserv.required,
      adult_rate:this.validserv.required,
      is_paid_child:false,
    })
  }
  SetMealAddOn(data){
    this.MealAddForm.get('extranet_meal_addon_id').setValue(data.extranet_meal_addon_id);
    this.MealAddForm.get('extranet_meal_plan_id').setValue(data.extranet_meal_plan_id);
    this.MealAddForm.get('addon_name').setValue(data.addon_name);
    this.MealAddForm.get('currency').setValue(data.currency);
    this.MealAddForm.get('adult_rate').setValue(data.adult_rate);
    this.MealAddForm.get('is_paid_child').setValue(data.is_paid_child);
    if(data.child_range_1_from || data.child_range_1_to || data.child_range_1_rate){
      this.PaidChildArr(true);
      this.MealAddForm.controls['ExtranetChildAgeRange']['controls'][0].get('from_age').setValue(data.child_range_1_from ? data.child_range_1_from  : 0);
      this.MealAddForm.controls['ExtranetChildAgeRange']['controls'][0].get('to_age').setValue(data.child_range_1_to ? data.child_range_1_to  : 0);
      this.MealAddForm.controls['ExtranetChildAgeRange']['controls'][0].get('child_rate').setValue(data.child_range_1_rate ? data.child_range_1_rate  : 0);
      if(data.child_range_2_from || data.child_range_2_to || data.child_range_2_rate){
        this.AddChildArr();
        this.MealAddForm.controls['ExtranetChildAgeRange']['controls'][1].get('from_age').setValue(data.child_range_2_from ? data.child_range_2_from  : 0);
        this.MealAddForm.controls['ExtranetChildAgeRange']['controls'][1].get('to_age').setValue(data.child_range_2_to ? data.child_range_2_to  : 0);
        this.MealAddForm.controls['ExtranetChildAgeRange']['controls'][1].get('child_rate').setValue(data.child_range_2_rate ? data.child_range_2_rate  : 0);
      }
    }
  }
  BackButton(){
    this.hotelmanageserv.Active_tab = 'HotelMeal';
    this.router.navigateByUrl(`Services/Hotel/HotelManage/${this.Extranet_Hotel_Id}`);
  }
  GetAllMeal(){
    this.apiserv.Get('/ExtranetMealAddon/GetAllExtranetMeal/EN').subscribe(res=>{
      if(res){
        this.MealPlan = res.data;
      }
    })
  }

  GetCurrency(event){
    if (event.value.length >= 2) {
      let obj ={
        langcode:'en',
        query:event.value
      }
      this.ddLoader = true;
      clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        this.apiserv.AdminGoPost(`/MasterSearch/GetAllCurrency`,obj).subscribe(res => {
          if (res) {
            this.CurrencyList = res.Result;
            this.ddLoader = false;
          }
        });
      }, 500);
    }
}
PaidChildArr(event){
  if(event){
    this.MealAddForm.addControl('ExtranetChildAgeRange',new FormArray([this.fb.group({
      from_age:this.validserv.required,
      to_age:this.validserv.required,
      child_rate:this.validserv.required,
    })]));
  }else {
    this.MealAddForm.removeControl('ExtranetChildAgeRange');
  }
}
AddChildArr(){
  let formArray = this.MealAddForm.controls['ExtranetChildAgeRange'] as FormArray;
  formArray.push(
    this.fb.group({
      from_age:['', Validators.compose([Validators.required,this.AmountRangeValidation(formArray.controls[0].get('to_age') ? formArray.controls[0].get('to_age').value : '')])],
      to_age:this.validserv.required,
      child_rate:this.validserv.required,
    })
  )
}
RemoveChildArr(i){
  let formArray = this.MealAddForm.controls['ExtranetChildAgeRange'] as FormArray;
  formArray.removeAt(i);
}
ChangeFeeMinValue(controlname,min,i?) {
  let min_amt = min;
  if (i == 0 || i) {
    this.MealAddForm.controls['ExtranetChildAgeRange']['controls'][i].get(controlname).clearValidators();
    this.MealAddForm.controls['ExtranetChildAgeRange']['controls'][i].get(controlname).addValidators([Validators.required, this.AmountRangeValidation(min_amt)]);
    this.MealAddForm.controls['ExtranetChildAgeRange']['controls'][i].get(controlname).markAsUntouched();
    this.MealAddForm.controls['ExtranetChildAgeRange']['controls'][i].get(controlname).setErrors(null);
    this.MealAddForm.controls['ExtranetChildAgeRange']['controls'][i].get(controlname).updateValueAndValidity();
  }else {
    this.MealAddForm.controls[controlname].clearValidators();
    this.MealAddForm.controls[controlname].addValidators([Validators.required, this.AmountRangeValidation(min_amt)]);
    this.MealAddForm.controls[controlname].markAsUntouched();
    this.MealAddForm.controls[controlname].setErrors(null);
    this.MealAddForm.controls[controlname].updateValueAndValidity();
  }
};
private AmountRangeValidation(initialValue): ValidatorFn {
  return (control: AbstractControl): { [key: string]: boolean } | null => {
    if (control.value || control.value == 0) {
      if (initialValue && parseInt(control.value) <= parseInt(initialValue)) {
        return { 'range': true };
      }
    }
    return null;
  };
}
Save(){
  if (this.MealAddForm.status == "VALID") {
    let val = this.MealAddForm.getRawValue();
    let reqObj={
      extranet_meal_addon_id: val.extranet_meal_addon_id ? val.extranet_meal_addon_id :'',
      extranet_hotel_id: this.Extranet_Hotel_Id,
      addon_name: val.addon_name,
      currency: val.currency,
      extranet_meal_plan_id: val.extranet_meal_plan_id,
      adult_rate: parseFloat(val.adult_rate),
      is_paid_child: val.is_paid_child,
    }
    if(val.ExtranetChildAgeRange && val.ExtranetChildAgeRange.length > 0){
      val.ExtranetChildAgeRange.forEach((child_obj,ind)=>{
        reqObj['child_range_'+(ind + 1)+'_from'] = child_obj.from_age;
        reqObj['child_range_'+(ind + 1)+'_to'] = child_obj.to_age;
        reqObj['child_range_'+(ind + 1)+'_rate'] = child_obj.child_rate ? parseFloat(child_obj.child_rate) : 0;
      })
    }
    this.apiserv.Post('/ExtranetMealAddon/SaveExtranetMealAddon',reqObj).subscribe(resp=>{
      if(resp){
        this.BackButton();
      }
      this.commonMasterSer.showMessage(resp.status,resp.message)
    })
  }else {
    this.validserv.showValidationsMsg(this.MealAddForm);
      setTimeout(() => {
        this.validserv.scrollToError();
      }, 50);
  }
}
  GetMealAddOnById() {
    if (this.Edit_Id) {
      this.apiserv.Get("/ExtranetMealAddon/GetExtranetMealAddonById/" + this.Edit_Id).subscribe(res=>{
        if(res){
          this.SetMealAddOn(res.data)
        }
      })
    } 
  }

}
