let fs = require('fs');
let PNG = require('pngjs2').PNG;
let concat = require('concat-frames');

async function read (file) {
	let img = await GetPNGPixels(file);
	let full = img.data;
	let outer = [];
	let alpha = [];

	for(let i=0, l=full.length;i<l;i++)
		(i % 4 === 3? alpha : outer).push(full[i]);
	
	img.data = new Buffer(outer);
	img.alpha = alpha;

	return img;
}

function write (path, img) {
	let outer = img.data;
	let alpha = img.alpha;
	let length = outer.length + alpha.length;
	let full = new Buffer(length);
	let ai = 0;
	let oi = 0;

	for(let i=0;i<length;i++) full[i] = (i % 4 === 3? alpha[ai++] : outer[oi++]);

	delete img.alpha;

	img.data = full;

	return new Promise(function (done, error) {
		img.pack().pipe(fs.createWriteStream(path)).on('finish', done).on('error', error);
	});
}

function GetPNGPixels (file) {
	return new Promise((done, error) => {
		try {
			let stream = fs.createReadStream(file);
			stream.on('error', error);
			stream.pipe(new PNG({ filterType: 4 })).on('parsed', function () {
				done(this);
			}).on('error', error);
		} catch (exc) { error(exc) }
	});
}

exports.read = read;
exports.write = write;