import { Component, OnInit, Input, AfterContentInit, Output, EventEmitter, OnDestroy, OnChanges, SimpleChanges } from '@angular/core';
import * as CIDR from 'ip-cidr';
import { Probe } from '@overflow/commons-typescript/model/probe';
import { DiscoverZone, DiscoverPort, DiscoverService } from '@overflow/commons-typescript/model/discovery';

@Component({
  selector: 'of-discovery-filter',
  templateUrl: './filter.component.html',
})
export class FilterComponent implements OnInit, AfterContentInit, OnDestroy, OnChanges {

  @Input() probe: Probe;
  @Input() requestStart: boolean;
  @Output() discoveryRequested = new EventEmitter<DiscoverZone>();

  private startIP: string;
  private endIP: string;
  private startPort: string;
  private endPort: string;
  private includeServices = [];

  private hostChecked = true;
  private portChecked = true;
  private serviceChecked = true;
  private tcpChecked = true;
  private udpChecked = true;

  constructor(
  ) {
  }

  ngOnInit() {
  }

  ngAfterContentInit() {
  }

  ngOnDestroy() {
  }

  hostRange() {
    if (!this.probe || this.probe === undefined) {
      return;
    }
    const cidr = new CIDR(this.probe.cidr);
    if (!cidr.isValid()) {
      alert('Invalid cidr : ' + this.probe.cidr);
      return;
    }
    this.startIP = cidr.addressStart.address;
    this.endIP = cidr.addressEnd.address;
  }

  portRange() {
    this.startPort = '1';
    this.endPort = '1024';
  }

  ngOnChanges(changes: SimpleChanges): void {
    if (changes['probe']) {
      this.hostRange();
      this.portRange();
    }
    if (changes['requestStart'] && this.requestStart) {
      this.onStart();
    }
  }

  onPortCheckChange(serviceCheckbox, checked) {
    if (!checked) {
      serviceCheckbox.checked = false;
      this.serviceChecked = false;
    }
  }

  onServiceCheckChange(portCheckbox, checked) {
    if (checked) {
      portCheckbox.checked = true;
      this.portChecked = true;
    }
  }

  onStart() {
    let discoverPort: DiscoverPort = null;
    let discoverService: DiscoverService = null;

    if (this.serviceChecked) {
      const services = new Array();
      for (const service of this.includeServices) {
        services.push(service.description); // FIXME to const name
      }
      discoverService = {
        includeServices: services,
      };
    }
    if (this.portChecked) {
      discoverPort = {
        firstScanRange: Number(this.startPort),
        lastScanRange: Number(this.endPort),
        includeTCP: this.tcpChecked,
        includeUDP: this.udpChecked,
        excludePorts: null,
        discoverService: discoverService
      };
    }
    const discoverZone: DiscoverZone = {
      discoverHost: {
        firstScanRangev4: this.startIP,
        lastScanRangev4: this.endIP,
        discoverPort: discoverPort
      },
    };

    this.discoveryRequested.emit(discoverZone);
  }
}
