---
import { ObjectId } from "mongodb";
import ItemCard from "../../../../components/ItemCard.astro";
import LoggedIn from "../../../../layouts/LoggedIn.astro";
import locationManager from "../../../../lib/classes/managers/LocationManager";
import { getName, getObj } from "../../../../lib/utils/langDriver";
import parseParams from "../../../../lib/utils/parseParams";
import { getAllSystems } from "../../../../lib/db/systems";

const { user, token, lang } = Astro.locals;

const currentSystemId = Astro.cookies.get('currentSystem')?.value ?? null;
if(currentSystemId === null) return Astro.redirect('/game/systemManager/select');

const currentSystem = locationManager.getSystem(new ObjectId(currentSystemId));
if(currentSystem === undefined) {
    Astro.cookies.delete('currentSystem');
    return Astro.redirect('/game/systemManager/select');
}

if(Astro.request.method === "POST") {
    const form = await Astro.request.formData();

	const source = form.get('toSystem') ?
			form.get('source-system')?.toString() :
			form.get('source-planet')?.toString();

	const fleetData = {
		source,
		destination: form.get('asteroid-id')?.toString(),
		mission: "MINE",
		ships: [{ id: "asteroid-miner", amount: 1 }],
		cargo: [],
        currentSystem: form.get('current-system')?.toString()
	}
    
	const response = await fetch(`${Astro.url.origin}/api/fleet/send`, {
		method: 'POST',
		headers: {
			'Content-Type': 'application/json',
			'Authorization': `Bearer ${token}`
		},
		body: JSON.stringify(fleetData)
	});

	console.log(await response.json());
	
	return Astro.redirect('/game/systemManager/asteroids');
}

const params = parseParams(Astro.request.url);

const systems = locationManager.getSystemsOwnedBy(user.id).map(sys => { return { id: sys.data._id, name: sys.data.name, hasAsteroidMiner: sys.ships.ships.find(ship => ship.data.id === "asteroid-miner") !== undefined, planets: sys.planets.map(planet => { return { id: planet._id, name: planet.name, hasAsteroidMiner: planet.ships.ships.find(ship => ship.data.id === "asteroid-miner") !== undefined } }) } });
---
<LoggedIn id="systemManager" title="System Manager">
    <h1><a href="/game/systemManager/asteroids">&lt;= go back</a>Sending</h1>
    <form method="post">
        <input type="hidden" name="asteroid-id" value={params.dest} />
        <input type="hidden" name="current-system" value={currentSystemId} />
        <label><input type="checkbox" name="fromSystem" />Send from system</label>
        <h3>System</h3>
        <select id="source-system" name="source-system"></select>
        <h3>Planet</h3>
        <select id="source-planet" name="source-planet"></select>
        <hr />
        <button type="submit">Send fleet</button>
    </form>
</LoggedIn>
<style>
* {
	color: white;
}

h1 {
    text-align: center;
    color: white;
}

h1 a {
    color: lime;
}

button {
    color: white;
    background-color: #555;
    padding: 0.5rem;
    border-radius: 5px;
    border: none;
    cursor: pointer;
}

.system-links {
    display: flex;
    flex-direction: row;
    justify-content: center;
    margin-bottom: 1rem;
}

a {
    color: white;
    background-color: #555;
    padding: 0.5rem;
    margin: 0 1rem;
    border-radius: 5px;
    text-decoration: none;
}

select {
	width: 10rem;
	height: 3rem;
	color: black;
	background-color: darkgray;
}
</style>
<script define:vars={{ systems }}>
const sourceSystem = document.getElementById('source-system');
const sourcePlanet = document.getElementById('source-planet');
const fromSystemCheckbox = document.querySelector('input[name="fromSystem"]');

if(!sourceSystem || !sourcePlanet || !fromSystemCheckbox) {
    console.error('Could not find all elements');
	return;
}

for(const system of systems) {
	const opt = document.createElement('option');
	opt.value = system.id;
	opt.innerText = system.hasAsteroidMiner ? system.name : `${system.name} (no miner)`;
	sourceSystem.appendChild(opt);
}

sourceSystem.addEventListener('change', () => {
	const system = systems.find(system => system.id === sourceSystem.value);
	if(!system) {
		sourcePlanet.innerHTML = '';
		const opt = document.createElement('option');
		opt.value = '';
		opt.innerText = 'No planets';
		sourcePlanet.appendChild(opt);
		return;
	}

	sourcePlanet.innerHTML = '';
		
	for(const planet of system.planets) {
		const opt = document.createElement('option');
		opt.value = planet.id;
		opt.innerText = planet.hasAsteroidMiner ? planet.name : `${planet.name} (no miner)`;
		sourcePlanet.appendChild(opt);
	}

	if(sourcePlanet.children.length === 0) {
		const opt = document.createElement('option');
		opt.value = '';
		opt.innerText = 'No planets';
		sourcePlanet.appendChild(opt);
	}
});

sourceSystem.dispatchEvent(new Event('change'));

fromSystemCheckbox.addEventListener('change', () => {
	sourcePlanet.disabled = fromSystemCheckbox.checked;
});
</script>