import DBBuilding from "../../types/db/DBBuilding";
import BuildingManager from "./managers/BuildingManager";

export default class Building {
    manager: BuildingManager
    data: DBBuilding;
    level: number;
    activePercent: number = 100;

    constructor(manager: BuildingManager, data: DBBuilding, level: number, activePercent?: number) {
        this.manager = manager;
        this.data = data;
        this.level = level;
        if(activePercent !== undefined) this.activePercent = activePercent;
    }

    async checkRequiredResources(level: number): Promise<boolean> {
        const resources = await this.manager.planet.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 playerBuildings = this.manager.buildings;
        let playerBuildingsCanBuild = { canBuild: true, missing: "" };
        this.data.requirements.buildings.forEach((buildingReq: any) => {
            if((playerBuildings.filter((building) => building.data.id === buildingReq.id)[0]?.level ?? 0) < buildingReq.level) {
                playerBuildingsCanBuild = { canBuild: false, missing: `${buildingReq.id} level ${buildingReq.level} required, found ${playerBuildings.filter((building) => building.data.id === buildingReq.id)[0]?.level ?? 0}` };
                return;
            }
        });
        if(!playerBuildingsCanBuild.canBuild) return {
            canBuild: false,
            error: playerBuildingsCanBuild.missing
        }

        // research
        const playerResearch = this.manager.planet.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: ""
        }
    }
}