import DBStructure from "../../types/db/DBStructure";
import StructureManager from "./managers/StructureManager";

export default class Structure {
    manager: StructureManager
    data: DBStructure;
    level: number;

    constructor(manager: StructureManager, data: DBStructure, level: number) {
        this.manager = manager;
        this.data = data;
        this.level = level;
    }

    async checkRequiredResources(level: number): Promise<boolean> {
        const resources = await this.manager.system.resources.calculateCurrentAvailableResources();

        const requirements = this.data.requirements.resources;

        let canBuild = true;

        for(let res of requirements) {
            const resource = resources.find(r => r.id === res.id);
            if(!resource) return false;

            const required = Math.pow(this.data.multiplier, level) * res.amount;

            if(resource.amount < required) {
                canBuild = false;
                break;
            }
        }

        return canBuild;
    }

    async checkRequirements(): Promise<{ canBuild: boolean, error: string }> {
        const playerStructures = this.manager.structures;
        let playerStructuresCanBuild = { canBuild: true, missing: "" };
        this.data.requirements.structures.forEach((structureReq: any) => {
            if(playerStructures.filter((structure) => structure.data.id === structureReq.id)[0]?.level ?? 0 < structureReq.level) {
                playerStructuresCanBuild = { canBuild: false, missing: `${structureReq.id} level ${structureReq.level} required, found ${playerStructures.filter((structure) => structure.data.id === structureReq.id)[0]?.level ?? 0}` };
                return;
            }
        });
        if(!playerStructuresCanBuild.canBuild) return {
            canBuild: false,
            error: playerStructuresCanBuild.missing
        }

        // research
        const playerResearch = this.manager.system.data.ownedBy.research;
        let playerResearchCanBuild = { canBuild: true, missing: "" };
        for(const researchReq of this.data.requirements.research) {
            if((playerResearch.research.find((research) => research.id === researchReq.id)?.level ?? 0) < researchReq.level) {
                playerResearchCanBuild = { canBuild: false, missing: `${researchReq.id} level ${researchReq.level} required, found ${playerResearch.research.find((research) => research.id === researchReq.id)?.level ?? 0}` };
            }
        };
        
        if(!playerResearchCanBuild.canBuild) return {
            canBuild: false,
            error: playerResearchCanBuild.missing
        }

        return {
            canBuild: true,
            error: ""
        }
    }
}