import { Component, OnInit } from '@angular/core';
import { ServerService } from './server.service';
import { AuthService } from '../core/services/auth.service';

@Component({
  selector: 'app-server',
  templateUrl: 'server.component.html',
  styles: [`
    .msg {
      max-height: 0;
      overflow: hidden;
      transition: max-height 0.5s ease-out;
      margin: 0;
    }
    #serverAddress {
      margin-top: 25px;
      cursor: pointer;
    }
  `]
})
export class ServerComponent implements OnInit {
  serverAddress = '176.188.217.1:54311';
  serverStartedChecked = false;
  serverStarted = false;
  errorMsg;
  warnMsg;
  successMsg;
  restarting = false;

  constructor(
    private serverService: ServerService,
    private authService: AuthService
  ) {}

  ngOnInit(): void {
    this.serverService.getStatus().subscribe(pServerStatus => {
      this.serverStartedChecked = true;
      this.serverStarted = pServerStatus === 1;
    });
  }

  isAuthenticated(): boolean {
    return this.authService.isAuthenticated();
  }

  restartServer(): void {
    this.restarting = true;

    this.serverService.restartServer().subscribe(() => {
      this.setMessage('Serveur redémarré.', 'successMsg');
    }, error => {
      this.setMessage('Une erreur est survenue lors du redémarrage du serveur.',
            'errorMsg');
    }, () => {
      this.restarting = false;
    });
  }

  startOrStopServer(): void {
    this.serverService[(this.serverStarted ? 'stop' : 'start') + 'Server']().subscribe(() => {
      this.setMessage('Serveur ' + (this.serverStarted ? 'éteint' : 'démarré') + '.', 'successMsg');
      this.serverStarted = !this.serverStarted;
    }, error => {
      if (error.status === 409) {
        this.setMessage('Le serveur est déjà '
            + (this.serverStarted ? 'éteint' : 'démarré') + '.',
            'warnMsg');
      } else {
        this.setMessage('Une erreur est survenue lors '
            + (this.serverStarted ? 'de l\'extinction' : 'du démarrage')
            + 'du serveur.',
            'errorMsg');
      }
    });
  }

  setMessage(message: string, type: string): void {
    this[type] = message;

    const resultMsgDiv = document.getElementById(type);
    resultMsgDiv.style.maxHeight = '64px';

    setTimeout(() => {
      resultMsgDiv.style.maxHeight = '0px';
      setTimeout(() => {
        this[type] = undefined;
      }, 550);
    }, 3000);
  }

  copyToClipBoard(): void {
    document.addEventListener('copy', (e: ClipboardEvent) => {
      e.clipboardData.setData('text/plain', (this.serverAddress));
      e.preventDefault();
      document.removeEventListener('copy', null);
      this.showCopiedMsg();
    });
    document.execCommand('copy');
  }

  showCopiedMsg(): void {
    document.getElementById('copiedMsg').style.display = '';
    setTimeout(() => {
      document.getElementById('copiedMsg').style.display = 'none';
    }, 1500);
  }
}
