var http = require("http");

export class HealthLib {
  private timerID;
  private options: any;
  /**
   * Состояние сервиса
   * 0 - не зарегистрирован,
   * 1 - зарегистрирован
   */

  private state: number = 0;
  constructor(host: string, port: number, version: number, name: string) {
    this.options = {
      host: host,
      port: +port,
      version: +version,
      name: name
    };
  }

  activation() {
    const postData = JSON.stringify(this.options);
    return new Promise((resolve, reject) => {
      var req = http.request(
        {
          hostname: "192.168.1.3",
          port: 1989,
          path: "/v1/registration",
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            "Content-Length": Buffer.byteLength(postData)
          }
        },
        function(res) {
          if (res.statusCode !== 200) {
            console.log("Не смог зарегистрироваться: [s] ", res.statusCode);
          } else {
            this.state = 1;
            console.log(
              "[*] Сервис зарегистрировался в точке доступа: [name] " + process.env.SERVICE_NAME);
          }
          resolve(this);
        }
      );

      req.write(postData);
      req.on("error", e => {
        this.state = 0;
        console.log("[ ] Не смог зарегистрироваться: [e] ", e.errno);
        this.health();
        resolve(this);
      });
      req.end();
    });
  }

  deactivation() {
    const postData = JSON.stringify(this.options);
    return new Promise((resolve, reject) => {
      var req = http.request(
        {
          hostname: "192.168.1.3",
          port: 1989,
          path: "/v1/deactivation",
          method: "DELETE",
          headers: {
            "Content-Type": "application/json",
            "Content-Length": Buffer.byteLength(postData)
          }
        },
        function(res) {
          if (res.statusCode !== 200) {
            console.log("[ ] Не смог зарегистрироваться: [s] ", res.statusCode);
          } else {
            this.state = 1;
            console.log(
              "[*] Сервис отвязан от точки доступа: [s] ",
              res.statusCode
            );
          }
          resolve(this);
        }
      );

      req.write(postData);
      req.on("error", e => {
        this.state = 0;
        console.log("Не смог зарегистрироваться: [e] ", e.errno);
        this.health();
        resolve(this);
      });
      req.end();
    });
  }
  health() {
    if (this.timerID) clearTimeout(this.timerID);
    this.timerID = setTimeout(() => {
      this.activation();
    }, 5000);
  }
}
