import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { MessageService } from 'primeng/api';
import { ValidationService } from 'src/app/core/common/validation.service';
import { EditActivityContractDetail } from 'src/app/core/models/Experience-Service/experience-rate-config-Edit/edit-details/edit-deatils.model';
import { API } from 'src/app/core/services/api.service';
import { CommonService } from 'src/app/core/services/common.service';

@Component({
  selector: 'app-modify-details',
  templateUrl: './modify-details.component.html',
})
export class ModifyDetailsComponent implements OnInit {

  FormData: FormGroup
  activityData;
  currencyList;
  activityContractId;
  include_nationality_list;
  exclude_nationality_list;
  all_nationality_list;
  constructor(
    private route: ActivatedRoute,
    public fb: FormBuilder,
    public APIServ: API,
    public validationService: ValidationService,
    public MsgService: MessageService,
    private router: Router
  ) { }


  ngOnInit(): void {
    this.OnintGroup()
    this.GetActivityById();
    this.GetAllCurrency();
    this.GetAllNationality();
    this.GetLOVKeys('Language')
    this.getRateConfig();
  }
  lovKeyDataObj = {
    Language: []
  }

  OnintGroup() {
    this.FormData = this.fb.group({
      experience_name: [''],
      option_name: this.validationService.required,
      currency_code: [''],
      _nationality_type: ['1'],
      is_exclude_nationality: [false],
      rate_inclusion: [''],
      contract_remark: [''],
      is_pickup_included: [false],
      is_drop_off_included: [false],
      is_guide_included: [false],
    });
  }

  GetActivityById() {
    let activity_id = CommonService.getSessionStoage('activity_id');
    this.APIServ.Get('/Activity/GetActivity/' + activity_id).subscribe(d => {
      if (d && d.status) {
        if (d.responseObject.activityContents && d.responseObject.activityContents.length > 0) {
          this.activityData = d.responseObject;
          this.FormData.get('experience_name').setValue(d.responseObject.activityContents[0].activity_name);

        }
      }
    });
  }

  getRateConfig() {
    this.route.queryParams.subscribe((obj) => {
      if (obj['id']) {
        this.activityContractId = obj['id'];
        this.APIServ.Get(
          '/ActivityContract/GetRateConfig/' + obj['id']
        ).subscribe((data) => {
          if (data) {
            this.SetValue(data.responseObject);
          }
        });
      }
    });
  }

  SetValue(data) {
    let value = this.FormData.getRawValue();
    Object.keys(value).forEach(e => {
      if (e == 'option_name' || e == 'currency_code' || e == 'rate_inclusion' || e == 'contract_remark' ||
        e == 'is_drop_off_included' || e == 'is_pickup_included') {
        this.FormData.get(e).setValue(data[e]);
      } else if (e == '_nationality_type') {
        this.FormData.get(e).setValue(data[e]);
        if (data[e] == '2') {
          this.isIncludeNationality(data[e]);
          let code = data['include_nationality_code'] ? data['include_nationality_code'].split(',') : [];
          this.FormData.get('include_nationality_code').setValue(code);
          this.remove_nationality('exclude');
        }
      } else if (e == 'is_exclude_nationality') {
        this.FormData.get(e).setValue(data[e]);
        if (data[e]) {
          this.isExcludeNationality(data[e]);
          let code = data['exclude_nationality_code'] ? data['exclude_nationality_code'].split(',') : [];
          this.FormData.get('exclude_nationality_code').setValue(code);
          this.remove_nationality('include');
        }
      } else if (e == 'is_guide_included') {
        this.FormData.get(e).setValue(data[e]);
        if (data[e]) {
          this.AddLangContorls(data[e])
          let Lngcode = data['guide_languages'] ? data['guide_languages'].split(',') : '';
          this.FormData.get('guide_languages').setValue(Lngcode);
        }
      }
    });
  }
  AddLangContorls(check) {
    if (check) {
      this.FormData.addControl('guide_languages', this.fb.control([], Validators.required));
    } else {
      this.FormData.removeControl('guide_languages');
    }
  }
  GetAllCurrency() {
    this.APIServ.Get('/Currency/GetCurrency').subscribe(d => {
      if (d) this.currencyList = d;
    });
  }


  isExcludeNationality(check) {
    if (check) {
      this.FormData.addControl('exclude_nationality_code', this.fb.control([[]], Validators.required));
      this.remove_nationality('include');
    } else this.FormData.removeControl('exclude_nationality_code');
  }

  isIncludeNationality(val) {
    if (val == '2') {
      this.FormData.addControl('include_nationality_code', this.fb.control([], Validators.required));
      this.FormData.get('include_nationality_code').setValue([]);
    } else if (val == '1') {
      this.FormData.removeControl('include_nationality_code');
      this.remove_nationality('exclude');
    }
  }

  remove_nationality(type) {
    let con = type == 'exclude' ? 'include_nationality_code' : 'exclude_nationality_code'
    type == 'exclude' ? this.exclude_nationality_list = [...this.all_nationality_list] : this.include_nationality_list = [...this.all_nationality_list];
    let list = type == 'exclude' ? this.exclude_nationality_list : this.include_nationality_list;
    let nationality_arr = this.FormData.get(con) ? this.FormData.get(con).value : [];
    nationality_arr.forEach(nationality_code => {
      let ind = list.findIndex(nationality_obj => nationality_obj.alpha_2_code == nationality_code);
      (ind != -1) ? list.splice(ind, 1) : '';
      type == 'exclude' ? this.exclude_nationality_list = [...list] : this.include_nationality_list = [...list];
    });
  }

  GetAllNationality() {
    this.APIServ.Get('/Country/GetCountry').subscribe(res => {
      if (res) {
        this.all_nationality_list = res;
        this.include_nationality_list = res;
        this.exclude_nationality_list = res;
      }
    });
  }
  GetLOVKeys(lov_key_names) {
    let lov_key_names_arr = lov_key_names.split(',');
    let lov_obj = {
      "lov_types": [],
      "lov_lang": "en"
    }
    lov_key_names_arr.forEach(key_name => {
      lov_obj.lov_types.push({ "lov_type": key_name });
    });
    this.APIServ.Post('/LovMaster/GetLov', lov_obj).subscribe(lov_data => {
      if (lov_data && lov_data.status) {
        this.GetActivityById();
        lov_key_names_arr.forEach(key_name => {
          let arr = lov_data.responseObject.filter(el => el.lov_type == key_name);
          arr.length > 0 ? this.lovKeyDataObj[key_name] = arr[0].keys : '';
        });
      }
    });
  }
  updateEditdetails() {
    let postdata = new EditActivityContractDetail();
    let value = this.FormData.getRawValue();
    postdata.contract_id = this.activityContractId;
    postdata.language_code = CommonService.getSessionStoage('Def_Lang_code');
    postdata.option_name = value.option_name;
    postdata.currency_code = value.currency_code;
    postdata._nationality_type = value._nationality_type;
    postdata.is_exclude_nationality = value.is_exclude_nationality;
    postdata.rate_inclusion = value.rate_inclusion;
    postdata.contract_remark = value.contract_remark;
    postdata.is_pickup_included = value.is_pickup_included;
    postdata.is_drop_off_included = value.is_drop_off_included;
    postdata.is_guide_included = value.is_guide_included;
    postdata.exclude_nationality_code = value.exclude_nationality_code ? value.exclude_nationality_code.join(',') : '';
    postdata.include_nationality_code = value.include_nationality_code ? value.include_nationality_code.join(',') : '';
    postdata.guide_languages = value.guide_languages ? value.guide_languages.join(',') : '';
    this.APIServ.Post('/ActivityContract/UpdateContractDetails', postdata).subscribe(res => {
      if (res) {
        this.showToastrMsg(res)
      }
    })


  }
  showToastrMsg(respData) {
    this.MsgService.add({
      severity: respData['status'] ? 'success' : 'error',
      detail: respData['message'],
    });
    setTimeout(() => {
      respData['status'] ? this.btnClick() : '';
    }, 500);
  }
  btnClick() {
    this.router.navigate(['/Services/ActivityServices/ExpServices/Manage'])
  }
}
