---
import { ObjectId } from 'mongodb';
import locationManager from '../lib/classes/managers/LocationManager';
import { getAllFleetByUser } from '../lib/db/fleet';
import SystemManager from '../lib/classes/managers/SystemManager';

const userId = new ObjectId(Astro.cookies.get('userid')?.value ?? '');

await locationManager.updateFleet();
const fleet = (await getAllFleetByUser(userId)).filter(f => new Date().getTime() - f.arrivalTime.getTime() < 0);
fleet.sort((a, b) => a.arrivalTime.getTime() - b.arrivalTime.getTime());

let own = 0;
let friendly = 0;
let enemy = 0;

for(const f of fleet) {
	const source = locationManager.findId(f.source);
	if(source !== null) {
		if(source instanceof SystemManager) {
			if(source.data.ownedBy.id.equals(userId)) own++;
			else if(!f.returning) {
				if(f.mission === "SPY" || f.mission === "ATTACK") enemy++;
				else friendly++;
			}
		} else {
			if(source.system.data.ownedBy.id.equals(userId)) own++;
			else if(!f.returning) {
				if(f.mission === "SPY" || f.mission === "ATTACK") enemy++;
				else friendly++;
			}
		}
	}
}
---
<div id="fleet-status">
    <table id="fleet-list">
        {fleet.map(f => {
            const source = locationManager.findId(f.source);
            const destination = locationManager.findId(f.destination);

            return (<tr class="fleet-item">
                <td class="fleet-item-text source">{source instanceof SystemManager ? source.data.name : source?.name}</td>
                <td class="fleet-item-text">{f.returning ? "<=" : "=>"}</td>
                <td class="fleet-item-text destination">{destination instanceof SystemManager ? destination.data.name : destination?.name}</td>
                <td class="fleet-item-text mission">{f.mission}</td>
                <td class="fleet-item-text arrival">{f.arrivalTime.toISOString()}</td>
                <td class="fleet-item-text eta"></td>
            </tr>)
        })}
    </table>
    <div id="fleet-count">
        <div class="fleet-count-own">{own}</div>
        <div class="horizontal-divider"></div>
        <div class="fleet-count-friendly">{friendly}</div>
        <div class="horizontal-divider"></div>
        <div class="fleet-count-enemy">{enemy}</div>
    </div>
</div>
<style>
#fleet-status {
    display: flex;
    color: white;
    background-color: #003953;
    width: 100%;
    min-height: 20px;
}

.fleet-item {
    margin-left: 20px;
    margin-right: 20px;
}

.fleet-item-text {
    font-weight: bold;
    margin-top: 5px;
    padding: 5px;
}

#fleet-count {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
    font-weight: bold;
    margin-left: auto;
    margin-right: 20px;
}

.fleet-count-own {
    color: #00ff00;
}

.fleet-count-friendly {
    color: #ffff00;
}

.fleet-count-enemy {
    color: #ff0000;
}

.horizontal-divider {
    width: 1px;
    height: 32px;
    background-color: #b0b0b0;
    margin-left: 20px;
    margin-right: 20px;
}
</style>
<script>
const eta = document.querySelectorAll('.eta');

function dateRemaining(date: Date) {
    const now = new Date();
    const diff = date.getTime() - now.getTime();
    const seconds = Math.floor(diff / 1_000);
    const minutes = Math.floor(seconds / 60);
    const hours = Math.floor(minutes / 60);
    const days = Math.floor(hours / 24);
    
    if(days > 0) return `${days}d ${hours % 24}h ${minutes % 60}m ${seconds % 60}s`;
    if(hours > 0) return `${hours}h ${minutes % 60}m ${seconds % 60}s`;
    if(minutes > 0) return `${minutes}m ${seconds % 60}s`;
    return `${seconds}s`;
}

function init() {
    for(const e of eta) {
        e.innerHTML = dateRemaining(new Date(e.parentElement?.children[4].innerHTML ?? ''));
        if(e.innerHTML === "0s") document.location.reload();
    }
}

init();

setInterval(init, 1_000);
</script>