---
import LoggedIn from "../../../layouts/LoggedIn.astro";
import User from "../../../lib/classes/User";
import locationManager from "../../../lib/classes/managers/LocationManager";

const user: User = Astro.locals.user;

if(Astro.request.method === "POST") {
    const selectedSystemId = (await Astro.request.formData()).get('systemId') as string | null;

    if(selectedSystemId !== null) {
        Astro.cookies.set('currentSystem', selectedSystemId, {
            path: '/',
            expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 7),
            sameSite: 'lax',
            secure: true
        });
        
        return Astro.redirect('/game/systemManager');
    }
}

const systems = locationManager.getSystemsOwnedBy(user.id);
---
<LoggedIn id="systemManager" title="System Manager">
    <div class="systems-list">
        {systems.map(system => (
            <div class="system-card">
                <h2>{system.data.name}</h2>
                <div><form method="post"><input type="hidden" name="systemId" value={system.data._id.toString()} /><input type="submit" value="Select" /></form></div>
            </div>
        ))}
    </div>
</LoggedIn>
<style>
.systems-list {
    display: flex;
    flex-direction: column;
    flex-wrap: wrap;
    justify-content: center;
}

.system-card {
    background-color: #333;
    color: white;
    padding: 1rem;
    margin: 1rem;
    border-radius: 5px;
    display: flex;
    flex-direction: row;
}

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

.system-card div {
    margin-top: auto;
    margin-bottom: auto;
    margin-left: 2rem;
}
</style>