import { readFileSync } from "fs";
import nodeHttp from "http";
import nodeHttps from "https";
import { read } from "snowboard-reader";
import { parse, fromRefract } from "snowboard-parser";

export function parseBinding(str) {
  const [hostStr, portStr] = str.split(":");
  const port = parseInt(portStr, 10);
  const host = hostStr === "" ? undefined : hostStr;

  return [host, port];
}

export function httpServer(app) {
  return nodeHttp.createServer(app);
}

export function httpsServer(app, cert, key) {
  return nodeHttps.createServer(
    {
      key: readFileSync(key),
      cert: readFileSync(cert)
    },
    app
  );
}

async function readAsRefract(input) {
  return parse(await read(input));
}

export async function readAsElement(input) {
  return fromRefract(await readAsRefract(input));
}

export async function readMultiAsElement(inputs) {
  return Promise.all(inputs.map(v => readAsElement(v)));
}

@@ -24,24 +24,56 @@
  from %22fs%22;%0A
+import %7B resolve %7D from %22path%22;%0A
 import nodeH
@@ -217,16 +217,269 @@
 rser%22;%0A%0A
+const templatePrefix = %22snowboard-theme-%22;%0A%0Aexport function detectTemplate(template) %7B%0A  try %7B%0A    const selected = require(%60$%7BtemplatePrefix%7D$%7Btemplate%7D%60);%0A    return selected.entrypoint;%0A  %7D catch %7B%0A    return resolve(process.cwd(), template);%0A  %7D%0A%7D%0A%0A
 export f

move detectTemplate helper to snowboard