---
import { ObjectId } from "mongodb";
import LoggedIn from "../../../../layouts/LoggedIn.astro";
import locationManager from "../../../../lib/classes/managers/LocationManager";

const { 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');
}

const discoveredAsteroids = currentSystem.asteroids.asteroids;
---
<LoggedIn id="systemManager" title="System Manager">
    <h1>Selected system: {currentSystem.data.name} <a href="/game/systemManager/select">(change)</a></h1>
    <div class="system-links">
        <a href="/game/systemManager">Overview</a>
        <a href="/game/systemManager/structures">System-wide structures</a>
        <a href="/game/systemManager/spaceStations">Space stations</a>
        <a href="/game/systemManager/asteroids">Asteroids</a>
    </div>
    <div>
        <h2>Avaliable asteroids <button id="scan">Scan for new</button></h2>
        <div>
            {discoveredAsteroids.map((asteroid) => <div>
                <h3>{asteroid.name} <a href={`/game/systemManager/asteroids/send?dest=${asteroid.id}`}>Send</a></h3>
                <h4>Resources left: </h4>
                {asteroid.resources.map((resource) => <div><p>{resource.id} - {resource.amount}</p></div>)}
            </div>)}
        </div>
    </div>
</LoggedIn>
<style>
* {
	color: white;
}

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

h1 a {
    color: lime;
}

button, a {
    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;
}

.system-links a {
    color: white;
    background-color: #555;
    padding: 0.5rem;
    margin: 0 1rem;
    border-radius: 5px;
    text-decoration: none;
}
</style>
<script>
async function scan() {
    await fetch('/api/system/asteroids/scan', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        }
    });

    window.location.reload();
}

document.getElementById('scan')?.addEventListener('click', scan);
</script>