#!/usr/bin/env node
'use strict';

const fs = require("fs");
const path = require("path");
process.chdir(path.resolve(__dirname, '../play.pokemonshowdown.com'));
const imageSize = require('image-size');

const Dex = require('./../caches/pokemon-showdown/dist/sim/dex').Dex;
const toID = Dex.toID;

process.stdout.write("Updating animated sprite dimensions... ");

let buf = `/*
DO NOT EDIT

THIS FILE IS AUTOGENERATED BY ./build-tools/build-minidex
*/

exports.BattlePokemonSprites = {
	substitute:{exists:false, front:{w:34, h:39}, back:{w:37, h:38}},
`;

let g5buf = `/*
DO NOT EDIT

THIS FILE IS AUTOGENERATED BY ./build-tools/build-minidex
*/

exports.BattlePokemonSpritesBW = {
`;

function sizeObj(objPath) {
	try {
		const size = imageSize(objPath);
		return {
			w: size.width,
			h: size.height,
		};
	} catch {}
}

function updateSizes() {
	for (const baseid in Dex.data.Pokedex) {
		const species = Dex.species.get(baseid);
		for (const formeName of [''].concat(species.cosmeticFormes || [])) {
			let spriteid = species.spriteid;
			if (formeName) spriteid += '-' + toID(formeName).slice(species.id.length);
			const id = toID(spriteid);

			{
				const row = { num: species.num };
				const frontSize = sizeObj('sprites/ani/' + spriteid + '.gif');
				if (frontSize) row.front = frontSize;
				const frontSizeF = sizeObj('sprites/ani/' + spriteid + '-f.gif');
				if (frontSizeF) row.frontf = frontSizeF;
				const backSize = sizeObj('sprites/ani-back/' + spriteid + '.gif');
				if (backSize) row.back = backSize;
				const backSizeF = sizeObj('sprites/ani-back/' + spriteid + '-f.gif');
				if (backSizeF) row.backf = backSizeF;
				if (row.front || row.back || !row.forme) {
					buf += `\t${id}:` + JSON.stringify(row).replace(/"/g, '') + `,\n`;
				}
			}

			{
				const g5row = { num: species.num };
				const frontSize = sizeObj('sprites/gen5ani/' + spriteid + '.gif');
				if (frontSize) g5row.front = frontSize;
				const frontSizeF = sizeObj('sprites/gen5ani/' + spriteid + '-f.gif');
				if (frontSizeF) g5row.frontf = frontSizeF;
				const backSize = sizeObj('sprites/gen5ani-back/' + spriteid + '.gif');
				if (backSize) g5row.back = backSize;
				const backSizeF = sizeObj('sprites/gen5ani-back/' + spriteid + '-f.gif');
				if (backSizeF) g5row.backf = backSizeF;
				if (g5row.front || g5row.back || !g5row.forme) {
					g5buf += `\t${id}:` + JSON.stringify(g5row).replace(/"/g, '') + `,\n`;
				}
			}
		}
	}

	buf = buf.slice(0, -2) + `
};
`;
	g5buf = g5buf.slice(0, -2) + `
};
`;

	fs.writeFileSync('data/pokedex-mini.js', buf);
	fs.writeFileSync('data/pokedex-mini-bw.js', g5buf);
}

if (fs.existsSync('sprites/ani/')) {
	updateSizes();
	console.log('DONE');
} else {
	try {
		fs.unlinkSync('data/pokedex-mini.js');
		fs.unlinkSync('data/pokedex-mini-bw.js');
	} catch {}
	console.log('SKIPPED');
}
