import { Component, OnInit, Input } from '@angular/core';
import { MatStepper, MatDialog } 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';

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

  agentDetail: any;
  channels: Array<any>;
  deploymentChannels: Array<any> = new Array<any>();
  dirty: boolean = true;
  step = -1;
  viewMode: boolean = false;

  constructor(
    private activatedRoute: ActivatedRoute,
    private agentService: AgentService,
    private matDialog: MatDialog,
    private translateService: TranslateService,
    private notificationService: NotificationService,
    private router: Router
  ) {

    this.viewMode = this.activatedRoute.snapshot.data.mode === 'view';

  }

  ngOnInit() {

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

      this.buildList();
    });
  }

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

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

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

          if (channel.id === deploymentChannel.channelId) {

            deploymentChannel.channelName = channel.name;
            deploymentChannel.channelImage = channel.image;
            deploymentChannel.active = (deploymentChannel.status === 'AC');


            for (let parameter of deploymentChannel.parameters) {
              for (let field of channel.parameters) {

                if (parameter.channelParamName === field.name) {
                  parameter.label = field.label;
                  parameter.type = field.type;
                  parameter.required = field.required;
                  parameter.traductions = field.traductions;
                  parameter.maxlength = field.maxlength;
                  break;
                }

              }
            }

            break;
          }
        }
      }
    }
  }

  addChannel() {
    mainLoop: for (let channel of this.channels) {
      channel.disabled = false;

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


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

    dialog.afterClosed().subscribe(result => {
      if (result) {
        let 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);
      }
    });
  }

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

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

  isDirty() {
    return this.dirty;
  }

  save() {

    let isValid: boolean = this.validate();

    if (!isValid) {
      return;
    }

    let 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 (let deploymentChannel of this.deploymentChannels) {
      let deploymentChannelTmp: any = {};

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

      for (let parameter of deploymentChannel.parameters) {
        let 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']);
      }
    });

  }

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

  validate(): boolean {
    let valid = true;

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

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

      for (let parameter of deploymentChannel.parameters) {
        if (!parameter.value) {
          valid = false;
          break mainLoop;
        }
      }

    }

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

    return valid;
  }

}
