import { parse } from "https://deno.land/std@0.106.0/flags/mod.ts";
import { createCanvas } from "https://deno.land/x/canvas@v1.3.0/mod.ts";
import { collageModeType, DisplayCollageModeType, displayCollageModeType, isCollageModeType, isDisplayCollageModeType } from "../src/common/collages.ts";
import {
  denoCollageModes,
  ProxyImage,
} from "./collages.ts";
import { CollageConfig } from "../src/common/types.ts";
import { choice, shuffle } from "../src/common/utils.ts";
import { walkSync } from "https://deno.land/std@0.107.0/fs/mod.ts";

const args = parse(Deno.args, {
  alias: {
    "w": "width",
    "h": "height",
    "o": "output",
    "m": "mode",
    "r": "recursive",
  },
  boolean: ["recursive"],
});

if (args["mode"] === true) {
  console.log(displayCollageModeType.join(", "));
  Deno.exit(0);
}

const files: Set<string> = new Set();
const includeExtensions = Array.from(
  String(args["include"] || "*.png, *.jpg").matchAll(/\*\.([\w]+)/g),
).map(([_, group]) => group);

args["_"].forEach((arg) => {
  arg = arg.toString();
  if (Deno.statSync(arg).isDirectory) {
    Array.from(
      walkSync(arg, {
        maxDepth: args["recursive"] ? Infinity : 1,
        includeDirs: false,
        includeFiles: true,
        exts: includeExtensions.length ? includeExtensions : undefined,
      }),
    ).forEach((entry) => files.add(entry.path));
  } else {
    files.add(arg);
  }
});

if (files.size < 2) {
  console.error("kollagen needs at least 2 images to work.");
  Deno.exit(1);
}

const shuffledFiles = shuffle(Array.from(files));

const images: ProxyImage[] = shuffledFiles.map((file) => new ProxyImage(file));

const allModeKeys: DisplayCollageModeType[] = [];
if (args["mode"]) {
  (args["mode"] as string).split(",").map((m) => m.trim()).forEach((m) => {
    if (isDisplayCollageModeType(m)) {
      allModeKeys.push(m)
    } else {
      throw Error(`"${m}" is not a valid collage mode.`);
    }
  })
} else {
  allModeKeys.push(...displayCollageModeType);
}

const canvas = createCanvas(args["width"] || 640, args["height"] || 640);
const context = canvas.getContext("2d");

const collageConfig: CollageConfig = {
  numImages: args["n"],
};
const modeKey: DisplayCollageModeType = choice(allModeKeys);

if (modeKey === "recursive") {
  console.log(
    `Creating a recursive collage, choosing from ${shuffledFiles.length} files...`,
  );
  await denoCollageModes.recursiveDraw(context, images, {
    modes: collageModeType,
    repeat: true,
    level: 3
  })
} else {
  const mode = denoCollageModes.modes[modeKey];
  console.log(
    `Creating a "${mode.name}" collage, choosing from ${shuffledFiles.length} files...`,
  );
  const segments = mode.getSegments(
    context,
    collageConfig,
    images,
  );
  mode.place(context, images, segments);
}

const output = args["output"] || "collage.png";
console.log(`Saving to "${output}"...`);
await Deno.writeFile(output, canvas.toBuffer());
