import { Component, OnInit, Input, ViewChild } 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 } from '@xdf/commons';
import { TranslateService } from '@ngx-translate/core';
import { Router, ActivatedRoute } from '@angular/router';
import { Form, FormArray, FormControl, FormGroup, FormGroupDirective, NgForm, Validators } from '@angular/forms';
import { ValidatorUtils } from '@xdf/gallery';

@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';
  isLoadingDataChannel = true;
  formGroup: FormGroup;

  constructor(
    private activatedRoute: ActivatedRoute,
    private agentService: AgentService,
    private matDialog: MatDialog,
    private translateService: TranslateService,
    private notificationService: NotificationService,
    private router: Router,
    private validatorUtils: ValidatorUtils
  ) {
    this.formGroup = new FormGroup({});
    this.mode = this.activatedRoute.snapshot.data.mode;
    this.viewMode = this.mode === 'view';
  }

  ngOnInit() {

    this.agentService.getChannelDatForWizard().pipe(first()).subscribe((result: any) => {
      if (result) {
        this.channels = result;
      } else {
        this.channels = [];
      }

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

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

  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) {

                if (parameter.channelParamName === 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;
                  formArray.addControl(field.name, new FormControl('', field.required ? [Validators.required] : []));
                  break;
                }

              }
            }

            break;
          }
        }
      }
    }
    console.log(this.formGroup);
  }

  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;

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

  deleteChannel(i) {
    this.deploymentChannels.splice(i, 1);
    this.buildAvaliableChannels();
  }

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

  isDirty() {
    return this.dirty;
  }

  save() {
    const isValid: boolean = this.validate();

    if (!isValid) {
      if (this.fieldFormList && this.fieldFormList.control) {
        this.fieldFormList.control.markAsTouched();
      }
      return;
    }

    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;
    agent.deploymentChannels = [];

    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.value = parameter.value;
        parameterTmp.channelParamName = parameter.channelParamName ? parameter.channelParamName : parameter.name;

        deploymentChannelTmp.parameters.push(parameterTmp);
      }

      agent.deploymentChannels.push(deploymentChannelTmp);
    }

    agent.frequentQuestions = this.agentDetail.frequentQuestions;

    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;
  }

  validate(): boolean {
    let valid = true;

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

      // if (!deploymentChannel.name) {
      //   valid = false;
      //   break;
      // }

      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) : [];
  }

}
