import {cachedFetchJSON} from './cache';
import {setupPopover} from './popover';

const warehouseNames = {
	'AI1': 'ANT',
	'CI1': 'BEN',
	'IC1': 'HRT',
	'NC1': 'MOR',
} as const;

const username = document.querySelector('#username') as HTMLInputElement;
const apiKey = document.querySelector('#api-key') as HTMLInputElement;
{
	const storedUsername = localStorage.getItem('fio-username');
	if (storedUsername)
		username.value = storedUsername;
	const storedApiKey = localStorage.getItem('fio-api-key');
	if (storedApiKey)
		apiKey.value = storedApiKey;
}
document.querySelector('#fetch')!.addEventListener('click', async () => {
	const supplyForDays = parseInt((document.querySelector('#days') as HTMLInputElement).value, 10);
	const loader = document.querySelector('#loader') as HTMLElement;
	loader.innerHTML = '';
	loader.style.display = 'block';
	try {
		await calculate(username.value, apiKey.value, supplyForDays);
		localStorage.setItem('fio-username', username.value);
		localStorage.setItem('fio-api-key', apiKey.value);
	} catch (e) {
		console.error(e);
	}
	loader.style.display = 'none';
});
document.querySelector('#buys')!.addEventListener('click', (event) => {
	if (!event.target) return;
	const target = event.target as HTMLElement;
	if (target.tagName !== 'INPUT' || (target as HTMLInputElement).type !== 'button') return;
	const xitSection = target.parentElement;
	if (!xitSection || !xitSection.classList.contains('xit-act')) return;
	navigator.clipboard.writeText(xitSection.querySelector('textarea')!.value);
});
setupPopover();

async function calculate(username: string, apiKey: string, supplyForDays: number): Promise<void> {
	const buys = document.querySelector('#buys')!;
	buys.innerHTML = '';

	const closest: Record<string, keyof typeof warehouseNames> = await cachedFetchJSON('/closest.json');
	const planetsByCX: Map<keyof typeof warehouseNames, Planet[]> = new Map();
	for (const planet of await getPlanets(username, apiKey)) {
		const wh = closest[planet.id];
		const existing = planetsByCX.get(wh);
		if (existing)
			existing.push(planet);
		else
			planetsByCX.set(wh, [planet]);
	}
	for (const [cx, planets] of planetsByCX)
		buys.append(...await calcForCX(username, apiKey, supplyForDays, planets, cx));
}

async function calcForCX(username: string, apiKey: string, supplyForDays: number, planets: Planet[],
		cx: keyof typeof warehouseNames): Promise<HTMLElement[]> {
	const prices = await getPrices(cx);
	const avail = await warehouseInventory(username, apiKey, warehouseNames[cx]);
	const {bids, orders} = await getBids(username, apiKey, cx);

	// what do we need and have
	const totalConsumption = new Map<string, number>();
	for (const planet of planets) {
		for (const [ticker, consumption] of planet.netConsumption)
			totalConsumption.set(ticker, (totalConsumption.get(ticker) ?? 0) + consumption);
		for (const mat of planet.exporting) {
			const planetExport = planet.inventory.get(mat);
			if (planetExport)
				avail.set(mat, (avail.get(mat) ?? 0) + planetExport);
		}
	}
	const buy = new Map<string, number>();
	for (const [mat, amount] of totalConsumption)
		if (amount > 0)
			buy.set(mat, (buy.get(mat) ?? 0) + amount * supplyForDays);

	// what's left to buy
	const materials: Material[] = [];
	for (const [mat, amount] of buy) {
		const remaining = Math.max(amount - (bids.get(mat) ?? 0) - (avail.get(mat) ?? 0), 0);
		const price = prices.get(mat);
		if (!price || price.Bid === null || price.Ask === null) {
			console.log(mat, 'has no bid/ask');
			continue;
		}
		const spread = price.Ask - price.Bid;
		materials.push({
			ticker: mat,
			amount,
			bids: bids.get(mat) ?? 0,
			have: avail.get(mat) ?? 0,
			spread,
			savings: spread * remaining,
		});
	}
	materials.sort((a, b) => b.savings - a.savings);

	const h2 = document.createElement('h2');
	h2.textContent = `${cx}/${warehouseNames[cx]}`;
	const span = document.createElement('span');
	span.textContent = planets.map(p => p.name).join(', ');
	const table = document.createElement('table');
	table.innerHTML = `
		<thead>
			<tr>
				<th>mat</th>
				<th data-tooltip="needed to supply all planets">want</th>
				<th>bids</th>
				<th data-tooltip="in warehouse">have</th>
				<th data-tooltip="want - bids - have">buy</th>
				<th data-tooltip="ask - bid">spread</th>
				<th data-tooltip="buy × spread">savings</th>
			</tr>
		</thead>
		<tbody></tbody>`;
	const tbody = table.querySelector('tbody')!;

	const toBuy: Record<string, number> = {};
	const priceLimits: Record<string, number> = {};
	const format = new Intl.NumberFormat(undefined, {maximumFractionDigits: 0}).format;
	for (const m of materials) {
		const tr = document.createElement('tr');
		const buyAmount = Math.max(m.amount - m.bids - m.have, 0);
		tr.innerHTML = `
			<td>${m.ticker}</td>
			<td>${format(m.amount)}</td>
			<td>${format(m.bids)}</td>
			<td>${format(m.have)}</td>
			<td>${format(buyAmount)}</td>
			<td>${format(m.spread)}</td>
			<td>${format(m.savings)}</td>
		`;
		if (buyAmount > 0) {
			if (m.bids === 0)
				tr.children[2].classList.add('red');
			toBuy[m.ticker] = Math.round(buyAmount);
			const bid = prices.get(m.ticker)!.Bid!;
			const epsilon = 10 ** (Math.floor(Math.log10(bid)) - 2);
			const limit = bid + 2 * epsilon;
			priceLimits[m.ticker] = limit;
		}
		tbody.appendChild(tr);
	}

	const xitSection = document.createElement('section');
	xitSection.classList.add('xit-act');
	xitSection.innerHTML = `
		<textarea readonly></textarea>
		<input type="button" value="copy">`;
	xitSection.querySelector('textarea')!.value = JSON.stringify({
		'actions': [
			{'name': 'BuyItems', 'type': 'CX Buy', 'group': 'A1', 'exchange': cx,
				'priceLimits': priceLimits, 'buyPartial': true, 'allowUnfilled': true, 'useCXInv': false},
		],
		'global': {'name': `${cx} buy orders for ${supplyForDays} days`},
		'groups': [{'type': 'Manual', 'name': 'A1', 'materials': toBuy}],
	});

	// deposits of current bids
	orders.sort((a, b) => (b.Limit * b.Amount) - (a.Limit * a.Amount));
	for (const order of orders) {
		const deposit = order.Limit * order.Amount;
		console.log(`${order.MaterialTicker.padEnd(4)} ${deposit}\n`);
	}

	return [h2, span, table, xitSection];
}

async function getPrices(cx: string) {
	const rawPrices = await cachedFetchJSON('https://refined-prun.github.io/refined-prices/all.json');
	const prices = new Map<string, RawPrice>();
	for (const p of rawPrices)
		if (p.ExchangeCode === cx)
			prices.set(p.MaterialTicker, p);
	return prices;
}

async function getPlanets(username: string, apiKey: string) {
	const fioBurns: FIOBurn[] = await cachedFetchJSON('https://rest.fnar.net/fioweb/burn/user/' + username,
			{headers: {'Authorization': apiKey}});
	const planets = fioBurns.map(burn => new Planet(burn));
	return planets;
}

async function warehouseInventory(username: string, apiKey: string, whName: string): Promise<Map<string, number>> {
	const warehouses: Warehouse[] = await cachedFetchJSON('https://rest.fnar.net/sites/warehouses/' + username,
			{headers: {'Authorization': apiKey}});
	
	const inventory = new Map<string, number>();
	for (const warehouse of warehouses)
		if (warehouse.LocationNaturalId === whName) {
			const storage: Storage = await cachedFetchJSON(`https://rest.fnar.net/storage/${username}/${warehouse.StoreId}`,
					{headers: {'Authorization': apiKey}});
			for (const item of storage.StorageItems)
				inventory.set(item.MaterialTicker, item.MaterialAmount);
			break;
		}
	return inventory;
}

async function getBids(username: string, apiKey: string, cx: string) {
	const allOrders: ExchangeOrder[] = await cachedFetchJSON('https://rest.fnar.net/cxos/' + username,
			{headers: {'Authorization': apiKey}});
	const orders = allOrders.filter(order =>
			order.OrderType === 'BUYING' && order.Status !== 'FILLED' && order.ExchangeCode === cx);
	const bids = new Map<string, number>();
	for (const order of orders)
		bids.set(order.MaterialTicker, (bids.get(order.MaterialTicker) ?? 0) + order.Amount);
	return {bids, orders};
}

class Planet {
	id: string;
	name: string;
	inventory: Map<string, number>;
	netConsumption: Map<string, number>;
	exporting: Set<string>; // producing more than consumption

	constructor(fioBurn: FIOBurn) {
		this.id = fioBurn.PlanetId;
		this.name = fioBurn.PlanetName || fioBurn.PlanetNaturalId;
		this.inventory = new Map();
		for (const item of fioBurn.Inventory)
			this.inventory.set(item.MaterialTicker, item.MaterialAmount);

		this.netConsumption = new Map<string, number>();
		for (const item of fioBurn.OrderProduction)
			this.netConsumption.set(item.MaterialTicker, -item.DailyAmount);

		for (const c of [...fioBurn.OrderConsumption, ...fioBurn.WorkforceConsumption]) {
			this.netConsumption.set(c.MaterialTicker, (this.netConsumption.get(c.MaterialTicker) ?? 0) + c.DailyAmount);
		}

		this.exporting = new Set<string>();
		for (const item of fioBurn.OrderProduction)
			if ((this.netConsumption.get(item.MaterialTicker) ?? 0) < 0)
				this.exporting.add(item.MaterialTicker);
	}
}

interface Material {
	ticker: string;
	amount: number;
	bids: number;
	have: number;
	spread: number;
	savings: number;
}

interface RawPrice {
	MaterialTicker: string;
	ExchangeCode: string;
	Bid: number | null;
	Ask: number | null;
	FullTicker: string;
}

interface ExchangeOrder {
	MaterialTicker: string;
	ExchangeCode: string;
	OrderType: 'SELLING' | 'BUYING';
	Status: 'FILLED' | 'PARTIALLY_FILLED';
	Amount: number;
	Limit: number;
}

interface StorageItem {
	MaterialTicker: string;
	MaterialAmount: number;
}

interface Storage {
	Name: string;
	StorageItems: StorageItem[];
	WeightLoad: number;
	VolumeLoad: number;
	Type: 'STORE' | 'WAREHOUSE_STORE' | 'FTL_FUEL_STORE' | 'STL_FUEL_STORE' | 'SHIP_STORE';
}

interface Warehouse {
	StoreId: string;
	LocationNaturalId: string;
}

interface Amount {
	MaterialTicker: string;
	DailyAmount: number;
}

interface FIOBurn {
	PlanetId: string;
	PlanetName: string;
	PlanetNaturalId: string;
	Error: any;
	OrderConsumption: Amount[];
	WorkforceConsumption: Amount[];
	Inventory: StorageItem[];
	OrderProduction: Amount[];
}
