import * as ejs from "ejs";
import { existsSync } from "fs";
import { createServer } from "http";

import { Article, asyncLoadJSON, CardItem, leanArticle, leanCard, MCMDB, onlyUnique } from "../lib";

const colorNames = {
  CL: "Colorless",
  MC: "Multicolor",
  W: "White",
  U: "Blue",
  B: "Black",
  R: "Red",
  G: "Green",
  WU: "Azorius",
  UB: "Dimir",
  BR: "Rakdos",
  RG: "Gruul",
  WG: "Selesnya",
  WB: "Orzhov",
  UR: "Izzet",
  BG: "Golgari",
  WR: "Boros",
  UG: "Simic",
  WUG: "Bant",
  WUB: "Esper",
  UBR: "Grixis",
  BRG: "Jund",
  WRG: "Naya",
  WBG: "Abzan",
  WUR: "Jeskai",
  UBG: "Sultai",
  WBR: "Mardu",
  URG: "Temur"
};

const columns: Record<string, (c: CardItem) => boolean> = {
  W: c => colorid(c.colorIdentity) == "W",
  U: c => colorid(c.colorIdentity) == "U",
  B: c => colorid(c.colorIdentity) == "B",
  R: c => colorid(c.colorIdentity) == "R",
  G: c => colorid(c.colorIdentity) == "G",
  MC: c => c.colorIdentity.length > 0,
  CL: c => colorid(c.colorIdentity) == "CL"
};

function wubrg(a: string, b: string) {
  const order = ["W", "U", "B", "R", "G"];
  const indexA = order.indexOf(a);
  const indexB = order.indexOf(b);
  return indexA - indexB;
}

function colorid(colors: string[]): string {
  if (colors.length < 1) {
    return "CL";
  }
  return colors.sort(wubrg).join("");
}

async function run() {
  if (process.argv.length < 3) {
    console.error("Usage: yarn fetch <uid>");
    process.exit(1);
    return;
  }
  const uid = process.argv[2];
  const uidCards = `${uid}-cards.json`;
  if (!existsSync("mcmCards.json")) {
    console.error("Card db is missing! Run 'yarn convert-db' first.");
    process.exit(1);
  }
  if (!existsSync(uidCards)) {
    console.error(`Could not find ${uidCards}! Run 'yarn fetch ${uid}' first.`);
    process.exit(1);
  }
  let db = await asyncLoadJSON<MCMDB>("mcmCards.json");
  let articles = await asyncLoadJSON<Article[]>(`${uid}-cards.json`);

  let cards: CardItem[] = articles
    .filter(art => art.idProduct in db)
    .map(art => {
      const card = db[art.idProduct];
      return {
        ...leanArticle(art),
        ...leanCard(card)
      };
    });

  let valid = cards
    .filter(
      c =>
        (c.language == "Italian" || c.language == "English") &&
        c.price <= 0.1 &&
        (c.rarity == "rare" || c.rarity == "mythic")
    )
    .filter(onlyUnique);

  const server = createServer(async (req, res) => {
    const template = await ejs.renderFile("templates/cube.ejs", {
      user: uid,
      cards: valid,
      columns,
      utils: { wubrg, colorNames, colorid }
    });
    res.end(template);
  });
  server.on("clientError", (err, socket) => {
    socket.end("HTTP/1.1 400 Bad Request\r\n\r\n");
  });
  server.listen(8000);
}

run();
