import { Component, OnInit, Input, ViewChild, ViewContainerRef } from '@angular/core';
import { MatStepper, MatDialog, ErrorStateMatcher, MatInput } from '@angular/material';
import { CaDeploymentChannelsModalComponent } from '../ca-deployment-channels-modal/ca-deployment-channels-modal.component';
import { AgentService } from '../../../service/agent.service';
import { first } from 'rxjs/operators';
import { NotificationType, NotificationService, InitCommonsService } from '@xdf/commons';
import { TranslateService } from '@ngx-translate/core';
import { Router, ActivatedRoute } from '@angular/router';
import { Form, FormArray, FormBuilder, FormControl, FormGroup, FormGroupDirective, NgForm, Validators } from '@angular/forms';
import { AuditDialogService, ConfirmationDialogService, DynaDataService, IFormView, ValidatorUtils } from '@xdf/gallery';
import { Dictionary, List } from '@amcharts/amcharts4/core';
import { iif, Subscription } from 'rxjs';

@Component({
  selector: 'byte-ca-deployment-channels',
  templateUrl: './ca-deployment-channels.component.html',
  styleUrls: ['./ca-deployment-channels.component.scss']
})
export class CaDeploymentChannelsComponent  implements OnInit {

  @Input()
  stepper: MatStepper;

  @Input()
  changes = false;

  @ViewChild('fieldForm', { static: false })
  fieldFormList: any;

  agentDetail: any;
  channels: Array<any>;
  deploymentChannels: Array<any> = new Array<any>();
  dirty = true;
  step = -1;
  viewMode = false;
  isAvaliableChannels = false;
  mode = 'new';
  detailText = 'Detail';
  titleText = 'Titulo';
  parameterTwilioNumber = 'twillio-number';
  isLoadingDataChannel = true;
  formGroup: FormGroup;
  registerForm: FormGroup;
  submitted = false;
  numbersForm: FormGroup;
  count = 0;
  loading=false;
  channelWhat = 'WhatsApp';
  changeFormSubscription: Subscription;
  // Parameters for channel
  twilio_parameters_numbers = [];
  twilio_parameters_country = {};
  twilio_parameters_countryCode={};
  current_index = 0;
  twilio_list_index = [];

  constructor(
    protected vcRef: ViewContainerRef,
    private activatedRoute: ActivatedRoute,
    protected router: Router,
    protected dynaDataService: DynaDataService,
    private translateService: TranslateService,
    protected notificationService: NotificationService,
    protected auditDialogService: AuditDialogService,
    protected confirmationDialogService: ConfirmationDialogService,
    protected init: InitCommonsService,
    private formBuilder: FormBuilder,
    private agentService: AgentService,
    private matDialog: MatDialog,
    private validatorUtils: ValidatorUtils,
  ) {
    
    this.formGroup = new FormGroup({});
    this.mode = this.activatedRoute.snapshot.data.mode;
    this.viewMode = this.mode === 'view';
  }



  protected disabledCondition(controlName?): boolean {
    const disabled = this.mode === 'view' || (this.mode === 'edit' && controlName === 'key');
    return disabled;
  }

  numericOnly(event) {
    let patt = new RegExp('[0-9]');
    let result = patt.test(event.key);
    console.log(result);
    if (result) {
      this.count++;
    }
    if (this.count >= 12) {
      return result = false;
    } else {
      return result;
    }
  }

  onCountryChange(event: any, index: number){
    //console.log(event)
    console.log('onCountryChange :  ',index,event.iso2);
    this.twilio_parameters_country[index] = event.iso2;
    this.twilio_parameters_countryCode[index]=event.dialCode;
  }

  generarNumbersString(numbers , countries, codes ){

    for (let index =0; index < numbers.length; index++){
      numbers[index]["codigoInternacional"] = codes[numbers[index]["indice"]];
      numbers[index]["pais"] = countries[numbers[index]["indice"]];
      numbers[index]["numero"] = this.numbersForm.controls[String(this.twilio_list_index[index])].value;
    }
    
    console.log(' JSON value : ',JSON.stringify({"telefono_despliegue": numbers}));
    return {"telefono_despliegue": numbers};
  }

  validatePhones(){
    console.log('  --- validando telefonos  ---- ',this.twilio_parameters_numbers.length);
    if(this.twilio_parameters_numbers.length == 0){
      this.notificationService.showMessage(this.translateService.instant('NOT.NUMBERS.ADDED'), undefined, NotificationType.error);
      return false;
    }
    console.log(this.twilio_parameters_numbers)
    for (const number of this.twilio_parameters_numbers){
      let numero_string = String(number.numero);
      if (!numero_string) {
        this.notificationService.showMessage(this.translateService.instant('NUMBER.NOT.COMPLETED'), undefined, NotificationType.error);
        return false;
      }
      else{
        console.log(' Numero a validar : ',numero_string,numero_string.length);
        var phoneno = /^[1-9]{1}[0-9]{6,11}$/;
        if (!numero_string.match(phoneno)) {
          this.notificationService.showMessage(this.translateService.instant('NO.VALID.NUMBER'), undefined, NotificationType.error);
          return false
        }
        // else if (numero_string.length < 9) {
        //   this.notificationService.showMessage('Faltan dígitos', undefined, NotificationType.error);
        //   return false
        // }
      }
    }
    return true;
  }

  ngOnInit() {

    this.agentService.getChannelDatForWizard().pipe(first()).subscribe((result: any) => {
      if (result) {
        this.channels = result;
      } else {
        this.channels = [];
      }
      console.log(' agent Detail : ',this.agentDetail);
      if(this.agentDetail.id){
        // deploymentChannels es una lista, como maximo 3 por ahora
        const deploymentChannels_array = this.agentDetail['deploymentChannels'];
        let order = 0;
        for(let i=0;i<deploymentChannels_array.length;i++){
          if(deploymentChannels_array[i]['channelName'] == this.channelWhat) order = i;
        }
        const parameters_array = deploymentChannels_array[order]['parameters'];
        // El parametro twilio-number es un json string
        // contiene todos los numeros
        // bucar el parametro twilio number
        // console.log('ARRAY')
        // console.log(parameters_array)
        let containsnumber=false;
        for(let i=0;i<parameters_array.length;i++){
          if(parameters_array[i].channelParamName==this.parameterTwilioNumber){
            containsnumber=true;
          }
        }
        if(containsnumber){
          
          const json_numbers = JSON.parse(parameters_array[2]['value']);
          // console.log(json_numbers)
          const numbers_json_array = json_numbers['telefono_despliegue'];
          const twilio_numbers_array = [];
  
          for (let index = 0; index < numbers_json_array.length; index++) {
            twilio_numbers_array.push({"numero":numbers_json_array[index]['numero'],
                                    "indice": index,
                                    "pais": numbers_json_array[index]['pais'],
                                    "codigoInternacional":numbers_json_array[index]['codigoInternacional']})
          }
          console.log('twilio_numbers_array : ',twilio_numbers_array);
          console.log('this.deploymentChannels : ',this.deploymentChannels);
          
          // console.log('this.deploymentChannels.parameters : ',);
          this.twilio_parameters_numbers = twilio_numbers_array;
        } 
        
      }
      
      this.buildList();
      this.buildAvaliableChannels();
      this.isLoadingDataChannel = false;

      // initialize number form
      
      this.numbersForm =this.buildNumbersForm();

      

    }, error => {
      this.isLoadingDataChannel = false;
    });

    
  }

  buildForm(agentDetail: any) {
    this.agentDetail = agentDetail;
    this.deploymentChannels = (agentDetail.deploymentChannels || []);
    this.buildList();
  }

  buildNumbersForm(): FormGroup{
    let form;
    form = this.formBuilder.group({});
    
    // Construye el grupo de formularios para los numeros
    for (let index = 0; index < this.twilio_parameters_numbers.length; index++) {
      form.addControl(String(index), new FormControl({ value: this.twilio_parameters_numbers[index]['numero'],disabled: this.viewMode},[Validators.required]));
      // if(this.mode=='view') form.addControl(String(index), new FormControl({ value: this.twilio_parameters_numbers[index]['numero'],disabled: true },[Validators.required]));
      // else form.addControl(String(index), new FormControl({ value: this.twilio_parameters_numbers[index]['numero'],disabled: false },[Validators.required]));
      // form.addControl(String(index), new FormControl(this.twilio_parameters_numbers[index]['numero'], [Validators.required]));
      this.current_index = this.current_index + 1; 
      this.twilio_list_index.push(index);
    }
    return form;
  }

  buildList() {
    if (this.channels && this.deploymentChannels) {

      for (const deploymentChannel of this.deploymentChannels) {
        for (const channel of this.channels) {

          if (channel.id === deploymentChannel.channelId) {
            deploymentChannel.channelName = channel.name;
            deploymentChannel.channelImage = channel.image;
            deploymentChannel.active = (deploymentChannel.status === 'AC');
            deploymentChannel.suggestTitle = channel.suggestTitle;
            deploymentChannel.suggestDetail = channel.suggestDetail;

            
            this.formGroup.addControl(channel.name, new FormGroup({}));


            for (const parameter of deploymentChannel.parameters) {
              for (const field of channel.parameters) {
                // console.log(' read field --- ',field);
                // console.log(' read oarameter :',parameter)
                if (parameter.channelParamName === field.name || parameter.name === field.name) {
                  // console.log(' agregando control --- ',field.name);
                  const formArray = this.formGroup.controls[channel.name] as FormGroup;
                  parameter.label = field.label;
                  parameter.type = field.type;
                  parameter.required = field.required;
                  parameter.traductions = field.traductions;
                  parameter.maxlength = field.maxlength;
                  parameter.regex = field.regex;
                  let field_value = parameter.value? parameter.value:'';
                  // en caso field_name sea twilio_number, 
                  if (field.name == this.parameterTwilioNumber) {
                    // formArray.addControl(field.name, this.buildNumbersForm());
                    formArray.addControl(field.name, new FormControl({value: field_value, disabled: this.viewMode},  [Validators.required] ));

                  }
                  else{
                    formArray.addControl(field.name, new FormControl({value: field_value, disabled: this.viewMode},  [Validators.required] ));
                    
                  }
                  // break;
                }

              }
            }

            break;
          }
        }
      }


    }
    this.registerForm = this.formBuilder.group({
      phone: ['', [Validators.required, Validators.minLength(10)]]
    });
    console.log(this.formGroup);
  }

  get f() { return this.registerForm.controls; }

  enablerer(option:Boolean){
    for (const deploymentChannel of this.deploymentChannels) {
      for (const channel of this.channels) {

        if (channel.id === deploymentChannel.channelId) {
          
          if(option) this.formGroup.controls[channel.name].disable()
          else this.formGroup.controls[channel.name].enable()

          for (const parameter of deploymentChannel.parameters) {
            for (const field of channel.parameters) {
              
              if (parameter.channelParamName === field.name || parameter.name === field.name) {
                // console.log(' agregando control --- ',field.name);
                const formArray = this.formGroup.controls[channel.name] as FormGroup;
                
                if (field.name == this.parameterTwilioNumber) {
                  // formArray.addControl(field.name, this.buildNumbersForm());
                  if(option) formArray.controls[field.name].disable()
                  else formArray.controls[field.name].enable()
                  
                }
                else{
                  if(option) formArray.controls[field.name].disable()
                  else formArray.controls[field.name].enable()
                  
                }
              }
            }
          }
          break;
        }
      }
    }
    for (const index of this.twilio_list_index){
      if(option) this.numbersForm.controls[String(index)].disable();
      else this.numbersForm.controls[String(index)].enable();
    }

  }


  onSubmit() {
    this.submitted = true;
    // stop here if form is invalid
    if (this.registerForm.invalid) {
      return;
    }
  }

  addNumber() {
    console.log(' Agregando numero ',this.current_index);
    let new_number = {"codigoInternacional":'51',"pais":'pe',"numero":"", "indice":this.current_index};

    this.twilio_parameters_numbers.push(new_number);
    this.twilio_list_index.push(this.current_index);

    this.numbersForm.addControl(String(this.current_index ), new FormControl('', []));

    this.current_index = this.current_index +1;
    console.log(' adfter add lista : ',this.twilio_list_index);

  }

  deleteNumber(index) {
    console.log(' eliminandi indice : ',this.twilio_list_index[index]);
    this.twilio_parameters_numbers.splice(index,1);

    this.numbersForm.removeControl(String(this.twilio_list_index[index]));
    this.twilio_list_index.splice(index,1);
    console.log(' after del lista : ',this.twilio_list_index);
    console.log(this.numbersForm.controls);
  }

  get numbers() {
    return (<FormArray>this.numbersForm.get('numbers')).controls;
  }

  buildAvaliableChannels() {
    this.isAvaliableChannels = false;
    mainLoop: for (const channel of this.channels) {
      channel.disabled = false;

      for (const deploymentChannel of this.deploymentChannels) {
        if (channel.id === deploymentChannel.channelId) {
          channel.disabled = true;
          continue mainLoop;
        }
      }
      if (!channel.disabled) {
        this.isAvaliableChannels = true;
      }
    }
  }

  addChannel() {
    const dialog = this.matDialog.open(CaDeploymentChannelsModalComponent, {
      width: '500px',
      data: {
        message: '',
        channels: this.channels
      }
    });

    dialog.afterClosed().subscribe(result => {
      if (result) {
        const selectedChannel = { ...result };


        selectedChannel.channelId = selectedChannel.id;
        selectedChannel.channelName = selectedChannel.name;
        selectedChannel.channelImage = selectedChannel.image;
        selectedChannel.id = undefined;
        selectedChannel.name = undefined;
        selectedChannel.parameters = selectedChannel.parameters;

        this.deploymentChannels.push(selectedChannel);
        this.setStep(this.deploymentChannels.length - 1);
        this.buildList();
        this.buildAvaliableChannels();
      }

    });
  }

  deleteChannel(i) {
    const ListChannelDeleted =this.deploymentChannels.splice(i, 1);
    for (const deploymentChannel of ListChannelDeleted){
      this.formGroup.removeControl(deploymentChannel.channelName);
      for(const parameter of deploymentChannel.parameters){
        const parameterTmp: any = {};
        parameterTmp.channelParamName = parameter.channelParamName ? parameter.channelParamName : parameter.name;
        if(parameterTmp.channelParamName == this.parameterTwilioNumber){
          for(const index in this.twilio_list_index){
            this.deleteNumber(index)
          }
        }
      }   
    }
    this.buildList();
    this.buildAvaliableChannels();
  }

  exit() {
    this.dirty = false;
    this.router.navigate(['/configuration/agent']);
  }

  isDirty() {
    return this.dirty;
  }

  saveAgent(){
    // this.viewMode=true;
    if(this.validar()){  
      if(this.agentService.getDeletedFiles().length>0){
        this.viewMode=true;
        this.loading=true;
        this.enablerer(true);
        var file= this.agentService.spliceDeletedFile();
        this.agentService.deleteFile(file[0]['uuid']).subscribe(res=>{
          if(res.message=='OK'){
            this.save();
            this.viewMode=false;
            this.loading=false;
            this.enablerer(false);
          }else{
            this.agentService.addDeletedFile(file[0]);
            const title = this.translateService.instant('title.information');
                const message = this.translateService.instant('NO.BUCKET.CONECTION');
                this.notificationService.showMessage(
                message,
                title,
                NotificationType.error
                 );
            this.viewMode=false;
            this.loading=false;
            this.enablerer(false);
          }
        })
      }
      else {
        this.save();
      }
    }

    // for(let deleted of this.agentService.getDeletedFiles()){
    //   console.log(deleted['uuid']);
    //   this.agentService.deleteFile(deleted['uuid']).subscribe(res=>{});
    // }
    // this.agentService.emptyDeletedFiles();
  }

  save() {
    const isValid: boolean =  this.validar(); //this.validate(); la validación requiere bind
    // this.viewMode=true;
    if (!isValid) {
      //Los datos estan mal
      if (this.fieldFormList && this.fieldFormList.control) {
        this.fieldFormList.control.markAsTouched();
      }
      return;
    }
    //si llega aqui los datos estan bien
    //aqui debes poner tu nueva condicion del knowledge
    const agent: any = {};

    agent.id = this.agentDetail.id;
    agent.name = this.agentDetail.name;
    agent.description = this.agentDetail.description;
    agent.version = this.agentDetail.version;
    agent.countryId = this.agentDetail.countryId;
    agent.timezone = this.agentDetail.timezone;
    agent.avatar = this.agentDetail.avatar;
    agent.language = this.agentDetail.language;
    agent.type = this.agentDetail.type;
    agent.status = this.agentDetail.status;

    // nuevo campo : periodo
    agent.period = this.agentDetail.period;
    agent.deploymentChannels = [];    

    //console.log(this.agentService.getfileData())
    if(this.mode=="create") agent.frequentQuestions = this.agentService.getfileData();
    else  agent.frequentQuestions = this.agentDetail.frequentQuestions;
    
    console.log('  -----------   submit agent  -----------');

    for (const deploymentChannel of this.deploymentChannels) {
      const deploymentChannelTmp: any = {};

      deploymentChannelTmp.id = deploymentChannel.id;
      deploymentChannelTmp.name = deploymentChannel.name;
      deploymentChannelTmp.status = deploymentChannel.active ? 'AC' : 'IN';
      deploymentChannelTmp.channelId = deploymentChannel.channelId;
      deploymentChannelTmp.parameters = [];

      for (const parameter of deploymentChannel.parameters) {
        const parameterTmp: any = {};
        
        parameterTmp.id = parameter.id;
        parameterTmp.name = parameter.channelParamName ? parameter.channelParamName : parameter.name;
        parameterTmp.channelParamName = parameter.channelParamName ? parameter.channelParamName : parameter.name;
        if (parameterTmp.channelParamName == this.parameterTwilioNumber) {
          parameterTmp.value = JSON.stringify(this.generarNumbersString(this.twilio_parameters_numbers, this.twilio_parameters_country, this.twilio_parameters_countryCode));
          if(!this.validatePhones()){
            return;
          }
        }
        else{
          parameterTmp.value = this.formGroup.controls[deploymentChannel.channelName].value[parameterTmp.name]; //this.formGroup.controls[deploymentChannel.channelName].controls[parameterTmp.name].value;  // parameter.value;
        }

        deploymentChannelTmp.parameters.push(parameterTmp);
      }

      agent.deploymentChannels.push(deploymentChannelTmp);
    }

    
    // console.log(this.formGroup);
    // console.log(this.numbersForm);
    // console.log(agent);
    // console.log(this.formGroup);
    // console.log(this.numbersForm);
    // console.log('DELETED');
    // console.log(this.agentService.getDeletedFiles());
    for(let deleted of this.agentService.getDeletedFiles()){
      console.log(deleted['uuid']);
      this.agentService.deleteFile(deleted['uuid']).subscribe(res=>{});
    }
    this.agentService.emptyDeletedFiles();
    //DESCOMENTAR
    this.agentService.update(agent.id, agent).pipe(first()).subscribe(() => {

      if (agent.id) {
        this.dirty = false;
        this.notificationService.showMessage(this.translateService.instant('agent.edit.success'), null, NotificationType.success);
        this.router.navigate(['/configuration/agent']);
      } else {
        this.dirty = false;
        this.notificationService.showMessage(this.translateService.instant('agent.create.success'), null, NotificationType.success);
        this.router.navigate(['/configuration/agent']);
      }
    });

  }

  onChange(fieldForm) {
    if (!fieldForm.control.touched) {
      fieldForm.control.markAsTouched();
    }
  }

  setStep(step) {
    this.step = step;
  }

  validar(): boolean {
    let valid=true;
    let active_channel=false;
    if(this.deploymentChannels.length==0) valid=false;
    mainLoop: for (const deploymentChannel of this.deploymentChannels) {
      const deploymentChannelTmp: any = {};
      for (const parameter of deploymentChannel.parameters) {
        const parameterTmp: any = {};
        parameterTmp.channelParamName = parameter.channelParamName ? parameter.channelParamName : parameter.name;
        parameterTmp.name = parameter.channelParamName ? parameter.channelParamName : parameter.name;
        if (parameterTmp.channelParamName == this.parameterTwilioNumber) {
          console.log('THIS CASE')
          parameterTmp.value = JSON.stringify(this.generarNumbersString(this.twilio_parameters_numbers, this.twilio_parameters_country,this.twilio_parameters_countryCode));
          if(!this.validatePhones()){
            valid=false;
            break mainLoop;
          }
        }
        else{
          parameterTmp.value = this.formGroup.controls[deploymentChannel.channelName].value[parameterTmp.name]; //this.formGroup.controls[deploymentChannel.channelName].controls[parameterTmp.name].value;  // parameter.value;
          if(parameterTmp.value==""){
            valid=false;
            break mainLoop;
          }
        }
      }
    }

    if (!valid) {
      this.notificationService.showMessage(this.translateService.instant('error.message.complete-form'), undefined, NotificationType.error);
    }else{
      for(const deploymentChannel of this.deploymentChannels){
        if(deploymentChannel.active) active_channel=true
      }
      if(!active_channel){
        valid=false;
        this.notificationService.showMessage(this.translateService.instant('no.active.channel'), undefined, NotificationType.error);
      } 
    } 

    return valid
  }

  validate(): boolean {
    let valid = true;
    
    mainLoop: for (const deploymentChannel of this.deploymentChannels) {
      const deploymentChannelTmp: any = {};

      for (const parameter of deploymentChannel.parameters) {
        parameter.error = false;
        if (!parameter.value) {
          valid = false;
          break mainLoop;
        }
        if (parameter.regex) {
          const regex = new RegExp(parameter.regex);
          if (!regex.test(parameter.value)) {
            parameter.error = true;
            valid = false;
            break mainLoop;
          }
        }
      }

    }

    if (!valid) {
      this.notificationService.showMessage(this.translateService.instant('error.message.complete-form'), undefined, NotificationType.error);
    }

    return valid;
  }

  getErrors(channelName: string, name: string, placeholder: string) {
    const channelFormGroup = (this.formGroup.controls[channelName] as FormGroup);
    return channelFormGroup ? this.validatorUtils.getErrors(channelFormGroup.controls[name] as FormControl, name, placeholder) : [];
  }

}
