import { Component, OnInit } from '@angular/core';
import { FormArray, FormBuilder, FormGroup } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { MessageService } from 'primeng/api';
import { ActivityContent } from 'src/app/core/models/Experience-Service/experience-manage-languag/experience-manage-lang.model';
import { API } from 'src/app/core/services/api.service';

@Component({
  selector: 'app-exp-manage-translation',
  templateUrl: './exp-manage-translation.component.html',
})
export class ExpManageTranslationComponent implements OnInit {

  constructor(private ApiServ: API, private router: Router, public MsgService : MessageService ,private route: ActivatedRoute, public fb: FormBuilder) { }
  formdata: FormGroup
  ServiceLanguages;
  Languages;
  ngOnInit(): void {
    this.GetLOVLanguage();
    this.GetDefaultActivity();
    this.formdata = this.fb.group({
      language_code: [''],
      def_language_code: [''],
      activity_name: [''],
      def_activity_name: [''],
      departure_point: [''],
      def_departure_point: [''],
      meeting_point: [''],
      def_meeting_point: [''],
      drop_point: [''],
      def_drop_point: [''],
      activity_highlight: [''],
      def_activity_highlight: [''],
      activity_description: [''],
      def_activity_description: [''],
      activity_restriction: [''],
      def_activity_restriction: [''],
      activities_details: [''],
      def_activities_details: [''],
      activity_inclusion: [''],
      def_activity_inclusion: [''],
      activity_exclusion: [''],
      def_activity_exclusion: [''],
      additional_pick_up_details: [''],
      def_additional_pick_up_details: [''],
      daywise_itinerary: this.fb.array([]),
    })
  }


  /**
   * @author Abdul Razzak
   * to get LOV data
   */
  GetLOVLanguage() {
    let formdata = {
      "lov_types": [{ "lov_type": "Language" }],
      "lov_lang": "en"
    }
    this.ApiServ.Post("/LovMaster/GetLov", formdata).subscribe(data => {
      if (data) {
        console.log(data)
        this.ServiceLanguages = data['responseObject']['0']['keys'];
        this.Languages = data['responseObject']['0']['keys'];
      }
    });
  };

  // GetActivityContent() {
  //   this.ApiServ.Get('/Activity/GetActivityContent/')
  // }
  activity_id;
  GetDefaultActivity() {
    this.route.queryParams.subscribe(d => {
      if (d['id']) {
        this.activity_id = d['id']
        this.GetActivityDetails(d['id'],'','def_');
      }
    });
  };

  getactivity(){
    let lang = this.formdata.get('language_code').value;
    this.GetActivityDetails(this.activity_id , lang , false);
  }
  GetActivityDetails(Id,lang,check){
    this.ApiServ.Get('/Activity/GetActivityContent/' + Id + '?LangCode=' + lang).subscribe(data => {
      if (data) {
        console.log(data,)
        this.Setvalue(data.responseObject, check)
      }
    });
  }
  Setvalue(data, check) {
    let value  = this.formdata.getRawValue()
    Object.keys(value).forEach(e => {
      let controlname = check ? check + e : e;
      if ( e == 'activity_name' || e == 'departure_point' 
        || e == 'meeting_point'
        || e == 'additional_pick_up_details'
        || e == 'drop_point' || e == 'activity_highlight' || e == 'activity_description'
        || e == 'activity_restriction' || e == 'activities_details' || e == 'activity_inclusion' || e == 'activity_exclusion'
      ) {
        this.formdata.get(controlname).setValue(data ? data[e] : '');
      }else if(e == 'language_code'){
        if(check){
          debugger
          this.formdata.get(controlname).setValue(data ? data[e] : ''); 
          let list = this.Languages
          let ind = this.Languages.findIndex(d => d.lov_value == data[e]);
          list.splice(ind, 1);
          this.Languages = [...list]
        } 
      } else if (e == 'daywise_itinerary') {
        if(data){
          let daywiseObj = JSON.parse(data[e]);
          if (daywiseObj.length > 0 && daywiseObj) {
            daywiseObj.forEach((e, l) => {
              check ?  this.CreateitineraryGroup(e) : '';
              let html = check ? check + 'Text_html' : 'Text_html';
              this.formdata.get('daywise_itinerary')['controls'][l].get(html).setValue(data ? e.Text_html : '');
            })
          }
        } else  this.cleardayswiseitinerary() 
      }
    })
  }

  cleardayswiseitinerary(){
    this.formdata.get('daywise_itinerary')['controls'].forEach(e => {
      e.get('Text_html').setValue('');
    })
  };

  CreateitineraryGroup(data) {
    let controller = this.formdata.get('daywise_itinerary') as FormArray;
    controller.push(this.fb.group({
      Text_html: [],
      def_Text_html: [],
      city_code: [data.city_code],
      country_code: [data.country_code],
    }));
  };

  SaveActivityLang(){
    let value = this.formdata.getRawValue();
    let postdata = new ActivityContent();
    postdata.activity_id = this.activity_id;
    postdata.activity_name = value.activity_name;
    postdata.supplier_id = '1232';
    postdata.language_code = value.language_code;
    postdata.departure_point = value.departure_point;
    postdata.meeting_point = value.meeting_point;
    postdata.additional_pick_up_details = value.additional_pick_up_details;
    postdata.drop_point = value.drop_point;
    postdata.activity_highlight = value.activity_highlight;
    postdata.activity_description = value.activity_description;
    postdata.activity_restriction = value.activity_restriction;
    postdata.activities_details = value.activities_details;
    postdata.activity_inclusion = value.activity_inclusion; 
    postdata.activity_exclusion = value.activity_exclusion; 
    let dayswiseitinerary = []

    if(value.daywise_itinerary){
      value.daywise_itinerary.forEach(e => {
        dayswiseitinerary.push({
          'Text_html' : e.Text_html,
          'country_code' : e.country_code,
          'city_code' : e.city_code,
        })
      })
    }
    postdata.daywise_itinerary = JSON.stringify(dayswiseitinerary);
    this.ApiServ.Post('/Activity/SaveContentDetails' ,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.navigateByUrl("/Services/ActivityServices/ExpServices/Search");
  };

}

