import * as plugins from './smartnginx.plugins';
import * as paths from './smartnginx.paths';
import { SmartNginx } from './smartnginx.classes.smartnginx';
import { NginxHost } from './smartnginx.classes.nginxhost';

import { Smartshell } from '@pushrocks/smartshell';

import { ChildProcess } from 'child_process';

/**
 * manages a nginxprocess for an NginxConfig
 */
export class NginxProcess {
  public started: boolean = false;
  public smartNginxRef: SmartNginx;
  private nginxChildProcess: ChildProcess;
  private smartshellInstance = new Smartshell({
    executor: 'bash'
  });

  constructor(nginxRefArg: SmartNginx) {
    this.smartNginxRef = nginxRefArg;
  }

  /**
   * start nginx
   */
  public async start() {
    if (!this.nginxChildProcess) {
      this.nginxChildProcess = (await this.smartshellInstance.execStreaming(
        `nginx -c ${paths.nginxConfFile}`
      )).childProcess;
    }
    this.started = true;
    plugins.smartlog.defaultLogger.log('info', 'started Nginx!');
  }

  /**
   * reload config
   */
  public async reloadConfig() {
    if (!this.started) {
      this.start();
    } else {
      await this.smartshellInstance.exec('nginx -s reload');
    }
    this.smartNginxRef.logger.log('info', 'NginxProcess has loaded the new config!');
  }

  /**
   * stop the nginx instance
   */
  public async stop() {
    if (this.nginxChildProcess) {
      this.smartshellInstance.exec('nginx -s quit');
      this.started = false;
      this.smartNginxRef.logger.log('info', 'stopped Nginx!');
    } else {
      this.smartNginxRef.logger.log('info', 'nginx already stopped!');
    }
  }

  /**
   * checks if nginx is in path
   */
  public check(): boolean {
    return;
  }
}
