#!/bin/nodejs

const componentToHex = (c) => ("0" + c.toString(16)).slice(-2);
const rgbToHex = (c) => componentToHex(c.r) + componentToHex(c.g) + componentToHex(c.b);
const hexToRgb = (hex) => {
    const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result ? {
        r: parseInt(result[1], 16), g: parseInt(result[2], 16), b: parseInt(result[3], 16)
    } : null;
};
  
const parseScheme = (str) => str.replace(/\s+/g, '').split(",").map(e=>hexToRgb(e))

const getTint = (c, w) => Math.round(c + (255 - c) * 1 * w);
const getShade = (c, w) => Math.round(c * w);

const tint = (c, w) => ({r:getTint(c.r, w), g:getTint(c.g, w), b:getTint(c.b, w)});
const shade = (c, w) => ({r:getShade(c.r, w), g:getShade(c.g, w), b:getShade(c.b, w)});

const tints = (c, w) => Array.from({ length: w }, (_, i) => tint(c, (i + 1)/w));
const shades = (c, w) => Array.from({ length: w }, (_, i) => shade(c, (i )/w));

const genPalette = (c, w=3) => [...tints(c, w).reverse(), Object.assign(c), ...shades(c, w).reverse()];


const fs = require("fs");

fs.readFile("palette.in", "utf-8", (_, buf) => {
    const colors = parseScheme(buf)
    .map(e=> genPalette(e, process.env.PALETTE_SIZE).filter(v=>(v.r+v.g+v.b>0)&&(v.r+v.g+v.b<765)))

    const hexstr = colors.map(cs=>cs.map(c=>rgbToHex(c)).join(',')).join(',')
    const gifstr = colors.map(cs=>cs.map(c=>`${c.r} ${c.g} ${c.b}`).join('\n')).join('\n')

    fs.writeFile("palette.out", hexstr, (err) => {
        if (err) console.log(err);
    });
    fs.writeFile("gifpalette.out", gifstr, (err) => {
        if (err) console.log(err);
    });
});
