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

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

  deploymentChannels: Array<any> = new Array<any>();
  channels: Array<any>;
  step = -1;

  constructor(
    private agentService: AgentService,
    private matDialog: MatDialog
  ) { }

  ngOnInit() {

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

      this.buildList();
    });
  }

  buildForm(agentDetail: any) {
    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;


            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() {
    let dialog = this.matDialog.open(CaDeploymentChannelsModalComponent, {
      width: '500px',
      data: {
        message: '',
        channels: this.channels
      }
    });

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

        selectedChannel.channelName = selectedChannel.name;
        selectedChannel.channelImage = selectedChannel.image;
        selectedChannel.name = undefined;

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

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

}
