import {
  Component,
  Input,
  OnInit,
  EventEmitter,
  Output,
  ViewChild,
  OnDestroy
} from '@angular/core';

import { of } from 'rxjs';
import { catchError, map, take } from 'rxjs/operators';

import { ProbeService } from '../service/probe.service';
import { Interface } from '@overflow/model/net/nic';
import { SelectItem } from 'primeng/primeng';
import { Zone } from '@overflow/model/discovery';
import { toMetaIPType, MetaIPType, MetaIPTypeEnum } from '@overflow/model/meta';
import { DropdownPanelComponent } from '@overflow/commons/ui/component/primeng';

class NICInfo {
  iface: string;
  friendlyName: string;
  metaIPType: MetaIPType;
  mac: string;
  address: string;
  network: string;
}

@Component({
  selector: 'app-nic-dropdown',
  templateUrl: './nic-dropdown.component.html',
  styleUrls: ['./nic-dropdown.component.scss']
})
export class NicDropdownComponent implements OnInit {
  @Input()
  blockTarget: any;
  @Output()
  select = new EventEmitter<Zone>();
  @ViewChild('panel')
  panel: DropdownPanelComponent;

  nics: SelectItem[] = [];
  selected: NICInfo;

  constructor(private probeService: ProbeService) {}

  ngOnInit(): void {
    this.probeService
      .call<Interface[]>('MachineService.Interfaces')
      .pipe(
        map((ifaces: Interface[]) => {
          ifaces.forEach(iface => {
            if (undefined === iface.addresses) {
              return;
            }
            iface.addresses.forEach(address => {
              if (
                address.metaIPType.key !== toMetaIPType(MetaIPTypeEnum.V4).key
              ) {
                return;
              }
              const nicInfo = {
                iface: iface.iface,
                friendlyName: iface.friendlyName,
                metaIPType: address.metaIPType,
                mac: iface.mac,
                address: address.address,
                network: address.network
              };
              this.nics.push({
                label: iface.friendlyName + ' (' + address.network + ')',
                value: nicInfo,
                disabled:
                  address.metaIPType.key !== toMetaIPType(MetaIPTypeEnum.V4).key
                    ? true
                    : false
              });
              if (address.gateway !== undefined && address.gateway.length > 0) {
                this.nicSelected(nicInfo);
              }
            });
          });
        }),
        catchError(error => {
          console.log(error);
          return of();
        }),
        take(1)
      )
      .subscribe();
  }

  nicSelected(nic: NICInfo) {
    this.selected = nic;

    const zone: Zone = {
      network: this.selected.network,
      iface: this.selected.iface,
      metaIPType: toMetaIPType(MetaIPTypeEnum.V4),
      address: this.selected.address,
      mac: this.selected.mac
    };
    this.select.emit(zone);

    this.panel.hide();
  }
}
