---
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";

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

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

    const request = await (await fetch(Astro.url.origin + '/api/structures/createStructure', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + token
        },
        body: JSON.stringify({
            system: currentSystemId,
            structureId: selectedStructureId
        })
    })).json();

    console.log(request);
}

const modalSet: { [key: string]: { resources: Array<any>, research: Array<any>, structures: Array<any>, energy: number } } = {};

const structureList = currentSystem.structures.structuresDB;
for(const structure of structureList) {
	modalSet[structure.id] = {
		resources: structure.requirements.resources.map(resource => {
			return {
				id: resource.id,
				amount: Math.pow(structure.multiplier, (currentSystem.structures.getStructureById(structure.id)?.level ?? 0) ) * resource.amount
			};
		}),
		research: structure.requirements.research,
		structures: structure.requirements.structures,
		energy: structure.energy
	};
}
---
<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 id="structure-modal-background">
		<div id="structure-modal-details" data-structure-id="">
			<h3>Required resources</h3>
			<div class="structure-modal-text" id="structure-modal-req-resources">None</div>
			<h3>Required structures</h3>
			<div class="structure-modal-text" id="structure-modal-req-structures">None</div>
			<h3>Required research</h3>
			<div class="structure-modal-text" id="structure-modal-req-research">None</div>
		</div>
	</div>
    <div class="structure-list">
        {currentSystem.structures.structuresDB.map(structure => (
            <ItemCard
                category="megastructures"
                id={structure.id}
                name={getName(lang, 'structures', structure.id)}
                image={`/images/structures/${structure.id}.jpeg`}
                level={(currentSystem.structures.getStructureById(structure.id)?.level ?? 0).toString()}
                description={getObj(lang, 'structures', structure.id).description ?? ""}
                button_type="general"
                button_name="nav-build"
            />
        ))}
    </div>    
</LoggedIn>
<style>
* {
	color: white;
}

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

h1 a {
    color: lime;
}

#structure-modal-background {
	display: none;
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background: rgba(0, 0, 0, 0.5);
	z-index: 100;
}

#structure-modal-details {
	display: none;
	position: fixed;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
	width: 80%;
	max-width: 800px;
	background: rgba(0, 0, 0, 0.9);
	border-radius: 8px;
	padding: 1rem;
	z-index: 101;
}

.structure-modal-text {
	font-size: 1.5rem;
}

.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;
}

.structure-list {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: space-evenly;
    color: white;
	row-gap: 40px;
	column-gap: 2%;
}

.structure-card div {
    margin-top: auto;
    margin-bottom: auto;
    margin-left: 2rem;
}
</style>
<script define:vars={{ modalSet, lang }}>
	const modalResources = document.getElementById("structure-modal-req-resources");
	const modalStructures = document.getElementById("structure-modal-req-structures");
	const modalResearch = document.getElementById("structure-modal-req-research");

	document.querySelectorAll('.item-card-info-button').forEach((el) => {
        el.addEventListener('click', () => {
            // modal
            const modalDiv = document.getElementById('structure-modal-details');
            if(!modalDiv) return;
            modalDiv.style.display = 'block';

			const reqResources = modalSet[el.parentElement.parentElement.dataset.id]?.resources ?? [];
			const reqStructures = modalSet[el.parentElement.parentElement.dataset.id]?.structures ?? [];
			const reqResearch = modalSet[el.parentElement.parentElement.dataset.id]?.research ?? [];

			modalResources.innerHTML = reqResources.length === 0 ? "None" : reqResources.map(resource => {
				return `${lang['resources'].find(r => r.id === resource.id).name}: ${resource.amount}`;
			}).join("<br />");

			modalStructures.innerHTML = reqStructures.length === 0 ? "None" : reqStructures.map(structure => {
				return `${lang['structures'].find(s => s.id === structure.id).name}: ${structure.level}`;
			}).join("<br />");

			modalResearch.innerHTML = reqResearch.length === 0 ? "None" : reqResearch.map(research => {
				return `${lang['research'].find(r => r.id === research.id).name}: ${research.level}`;
			}).join("<br />");

            // background
            const backgroundDiv = document.getElementById('structure-modal-background');
            if(!backgroundDiv) return;
            backgroundDiv.style.display = 'block';
        });
    });

    // close modal on background click
    const bg = document.getElementById('structure-modal-background');
    
    bg?.addEventListener('click', () => {
        const modalDiv = document.getElementById('structure-modal-details');
        if(!modalDiv) return;
        modalDiv.style.display = 'none';

        const backgroundDiv = document.getElementById('structure-modal-background');
        if(!backgroundDiv) return;
        backgroundDiv.style.display = 'none';
    });
</script>