#!/usr/env/bin node

import { writeFileSync } from 'fs';
import convert from './converter';

const input = process.argv.filter(i => i.slice(0, 2) !== '--')[2];

if (!input) {
	console.error('You need to pass an input filename.');
	process.exit(1);
}

const output = process.argv.filter(i => i.slice(0, 2) !== '--')[3];

const USING_OUTPUT = output != null

const HALVED = process.argv.slice(2).includes('--half');
const QUARTERED = process.argv.slice(2).includes('--quarter');

if (!output) {
	console.error('You need to pass an output filename.');
	process.exit(1);
}

convert(input, HALVED ? 2 : QUARTERED ? 4 : 1)
	.then(buf => {
		if (USING_OUTPUT)
			writeFileSync(output, buf.map(r => r.map(c => `${c.red.toString(16).padStart(2, '0')}${c.green.toString(16).padStart(2, '0')}${c.blue.toString(16).padStart(2, '0')}`)).map(r => r.join('')).join('\n'));
		else
			console.log(buf.map(r => r.map(c => `${c.red.toString(16)}${c.green.toString(16)}${c.blue.toString(16)}`)).map(r => r.join('')).join('\n'));
	}).catch(e => {
		console.error(`Something went wrong, error follows.`);
		console.error(e);
		process.exit(1);
	})