import { spawn } from "child_process";

import { NBootstrapDialHelper, NBootstrap } from "@nanoapp/proxy"

class RemoteNBootstrap extends NBootstrap {
  constructor(addr, port_forward) {
    super("http://"+addr)
    this.port_forward = port_forward
    this.proxy_addr = addr;
  }

  async WhetherInstalled() {
    await this.port_forward("127.0.0.1:7890", this.proxy_addr)
    return super.WhetherInstalled()
  }

  async LaunchProxy(progs, progressFN) {
    try {
      const pinfo = await super.LaunchProxy(progs, progressFN)
      const addr = pinfo.getAddrsList()[0].slice(7)
      await this.port_forward(addr, addr)
      return pinfo
    } catch (e) {
      throw(e)
    }
  }
}

export class Machine {
  constructor({ip, user, appid}) {
    const forward = async (from, to) => {
      let proc = spawn("ssh", ["-C", "-q", "-N", "-L", `${to}:${from}`, `${user}@${ip}`])
      console.log("ssh", "-C", "-q", "-N", "-L", `${to}:${from}`, `${user}@${ip}`)
      return proc
    }

    this.appid = appid
    const addr = "127.0.0.1:7778"
    this.nbootstrap = new RemoteNBootstrap(addr, forward)
  }

  GetNAPI(napi) {
    if (!this.dialhelper) {
      this.dialhelper = new NBootstrapDialHelper(this.nbootstrap)
      this.dialhelper.setAppId(this.appid)
    }
    return new napi(this.dialhelper)
  }
}
