import * as vscode from 'vscode';
import { window, StatusBarItem } from 'vscode';

const statusBarPos = 1;

export default class StatusBar {
  private readonly _stopRunItem: StatusBarItem;
  private readonly _connectedItem: StatusBarItem;

  private _isRunningAvailable: boolean = false;
  private _isInTransition: boolean = false;
  private _isRunning: boolean = false;
  private _isConnected: boolean = false;
  private _temporaryMessage?: string;
  private _temporaryMessageTimer?: NodeJS.Timeout;

  constructor() {
    this._stopRunItem = window.createStatusBarItem(vscode.StatusBarAlignment.Left, statusBarPos);
    this._connectedItem = window.createStatusBarItem(vscode.StatusBarAlignment.Left, statusBarPos);
    this.update();
  }

  public subscribe(subscriptions: { dispose(): any }[]) {
    subscriptions.push(this._stopRunItem);
    subscriptions.push(this._connectedItem);
    this._connectedItem.show();
  }

  public setRunAvailable(value: boolean = true) {
    this._isRunningAvailable = value;
    this.update();
  }

  public setConnected(value: boolean = true) {
    this._isConnected = value;
    this.update();
  }

  public setInTransition(value: boolean = true) {
    this._isInTransition = value;
    this.update();
  }

  public setRunning(value: boolean = true) {
    this._isRunning = value;
    this.update();
  }

  public setTemporaryMessage(value: string, duration: number = 3000) {
    if (this._temporaryMessageTimer) {
      clearTimeout(this._temporaryMessageTimer);
    }
    this._temporaryMessage = value;
    this.update();
    this._temporaryMessageTimer = setTimeout(() => {
      this._temporaryMessageTimer = undefined;
      this._temporaryMessage = undefined;
      this.update();
    }, duration);
  }

  private update() {
    if (this._isRunningAvailable) {
      const stopRunItem = this._stopRunItem;
      stopRunItem.command = this._isRunning ? 'sculpt-ui.stop' : 'sculpt-ui.start';
      const iconName = this._isInTransition ? 'loading~spin' : this._isRunning ? 'debug-stop' : 'debug-start';
      const tempMsg = this._temporaryMessage ? ' - ' + this._temporaryMessage : '';
      stopRunItem.text = `$(${iconName}) ${this._isRunning ? 'Stop' : 'Start'}${
        this._isInTransition ? 'ing' : ''
      } SculptUI${tempMsg}`;
      stopRunItem.tooltip = this._isInTransition
        ? ''
        : this._isRunning
        ? 'Click to stop the SculptUI dev server.'
        : 'Click to start your application in the SculptUI dev server.';
      stopRunItem.show();
    } else {
      this._stopRunItem.hide();
    }
    if (this._isConnected) {
      const connectedItem = this._connectedItem;
      connectedItem.text = '$(vm-active)';
      connectedItem.tooltip = 'SculptUI client(s) are connected!';
      /* TODO: connectedItem.command =  */
      connectedItem.show();
    } else {
      this._connectedItem.hide();
    }
  }
}
