import { Component, OnInit, Inject, AfterContentInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Store, select } from '@ngrx/store';
import { RPCClientError } from '@loafer/ng-rpc/protocol';
import * as DetailStore from '../../store/detail';
import { DetailSelector } from '../../store';
import { Probe } from '../../model';
import { ConfirmationService } from 'primeng/primeng';
import * as CIDR from 'ip-cidr';
// import { SettingComponent as DiscoverySettingComponent } from 'packages/discovery/component/setting/setting.component';


@Component({
  selector: 'of-probe-detail',
  templateUrl: './detail.component.html',
  providers: [ConfirmationService]
})
export class DetailComponent implements OnInit, AfterContentInit {

  probe$ = this.detailStore.pipe(select(DetailSelector.select('probe')));
  probe: Probe = null;
  IPRange: string;
  display = false;

  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private detailStore: Store<DetailStore.State>,
    private confirmationService: ConfirmationService
  ) { }

  ngOnInit() {
    this.probe$.subscribe(
      (probe: Probe) => {
        if (probe) {
          this.probe = probe;
          this.arrangeInfo();
        }
      },
      (error: RPCClientError) => {
        console.log(error.response.message);
      }
    );
  }

  ngAfterContentInit() {
    const probeId = this.route.snapshot.paramMap.get('id');
    this.detailStore.dispatch(
      new DetailStore.Read(
        { id: probeId }
      )
    );
  }

  arrangeInfo() {
    const cidr = new CIDR(this.probe.cidr);
    if (!cidr.isValid()) {
      return;
    }
    this.IPRange = cidr.addressStart.address + ' ~ ' + cidr.addressEnd.address;
  }

  onDiscoveryClick() {
    this.display = true;
  }

  onDiscoverycloseDialog() {
    this.display = false;
  }

  onRemoveClick() {
    this.confirmationService.confirm({
      header: 'Confirmation',
      icon: 'fa fa-trash',
      message: 'Are you sure to remove this Probe?',
      accept: () => {
        this.router.navigate(['probes/list']);
      },
      reject: () => {
      }
    });
  }
}

