import { Component, Input, Output, EventEmitter, ViewChild, OnInit, OnChanges, SimpleChanges } from '@angular/core';
import { Probe, ProbeHost } from '@overflow/commons-typescript/model/probe';
import { MessageService } from 'primeng/components/common/messageservice';
import { Message } from 'primeng/primeng';

@Component({
  selector: 'of-probe-detail',
  templateUrl: './detail.component.html',
  providers: [MessageService]
})
export class ProbeDetailComponent implements OnChanges {

  @Input() pending: boolean;
  @Input() probeHost: ProbeHost;
  @Output() modify = new EventEmitter<ProbeHost>();
  @Output() discovery = new EventEmitter<number>();

  connectionStatus: Message[] = [];

  editMode = false;
  displayNameErrMsg: string;
  descriptionErrMsg: string;
  displayName: string;
  description: string;

  constructor(private messageService: MessageService) {
  }

  ngOnChanges(changes: SimpleChanges): void {
    if (changes['probeHost']) {
      this.checkConnectStatus();
    }
  }

  checkConnectStatus() {
    this.connectionStatus = [];
    const msg = this.probeHost.probe.connectDate ? {
      severity: 'success',
      summary: 'Connected',
      detail: this.probeHost.probe.connectAddress
    } : {
      severity: 'warn', // info, warn, error
      summary: 'Not Connected',
    };
    this.connectionStatus.push(msg);
  }

  onDisplayNameEditing(value: string) {
    const msg: string = this.checkValidDisplayName(value);
    if (msg !== null) {
      this.displayNameErrMsg = msg;
    } else {
      this.displayNameErrMsg = null;
      this.displayName = value;
    }
  }

  onDescriptionEditing(value: string) {
    const msg: string = this.checkValidDescription(value);
    if (msg !== null) {
      this.descriptionErrMsg = msg;
    } else {
      this.descriptionErrMsg = null;
      this.description = value;
    }
  }

  onEditSave() {
    this.probeHost.probe.displayName = this.displayName;
    this.probeHost.probe.description = this.description;
    this.modify.emit(this.probeHost);
    this.editMode = false;
  }

  onDiscoveryClick() {
    this.discovery.emit(this.probeHost.id);
  }

  checkValidDisplayName(value: string): string | null {
    if (value.length <= 2 || value.length > 20) {
      return 'displayname length : 3 ~ 20';
    }
    const regex = /[`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi;
    if (value.match(regex)) {
      return 'Cannot use special characters.';
    }
    return null;
  }

  checkValidDescription(value: string): string | null {
    if (value.length > 50) {
      return 'description length : 0 ~ 50';
    }
    const regex = /[`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi;
    if (value.match(regex)) {
      return 'Cannot use special characters.';
    }
    return null;
  }
}