import { getAllResources } from "../../db/resources";
import { updateSystemResources } from "../../db/systems";
import SystemManager from "./SystemManager";
import ResourceManager from "./abstract/ResourceManager";

export default class SystemResourceManager extends ResourceManager {
    system: SystemManager;

    constructor(system: SystemManager) {
        super();
        this.system = system;
    }

    async init(resourceData?: { id: string, amount: number }[]) {
        const resources = await getAllResources();

        this.resourcesDB = resources;

        if(!resourceData || resourceData.length === 0) {
            resourceData = [
                {
                    id: "coal",
                    amount: 11
                },
                {
                    id: "iron",
                    amount: 22
                },
                {
                    id: "gold",
                    amount: 33
                },
                {
                    id: "water",
                    amount: 44
                },
                {
                    id: "sulfuric-acid",
                    amount: 55
                },
                {
                    id: "liquid-nitrogen",
                    amount: 66
                },
                {
                    id: "hydrogen",
                    amount: 77
                },
                {
                    id: "oxygen",
                    amount: 88
                },
                {
                    id: "helium-3",
                    amount: 99
                }
            ];

            await updateSystemResources(this.system.data._id, this.resources);
        }
    
        resourceData.forEach(resource => {
            const resFromDB = resources.find(res => res.id === resource.id);
            if(resFromDB) this.resources.push({
                id: resource.id,
                amount: resource.amount,
                lastUpdated: null,
                perHourMiningRate: 0,
                data: resFromDB
            })
        });

        return this;
    }

    getStorageCapacities(): { id: string; capacity: number; }[] {
        return this.resources.map(res => {
            return {
                id: res.id,
                capacity: 10_000 //TODO: add structure for storage
            }
        });
    }

    async sync() {
        await updateSystemResources(this.system.data._id, this.resources.map(res => {
            return {
                id: res.id,
                amount: res.amount,
                lastUpdated: res.lastUpdated,
                perHourMiningRate: res.perHourMiningRate
            }
        }));
    }
}