import { getAllBuildings } from '../../db/buildings';
import DBBuilding from '../../../types/db/DBBuilding';
import { Planet } from './PlanetManager';
import { updatePlanetBuildings } from '../../db/planets';
import Building from '../Building';

export default class BuildingManager {
    buildings: Array<Building> = [];
    buildingsDB: Array<DBBuilding> = []
    planet: Planet;

    constructor(planet: Planet) {
        this.planet = planet;
    }

    async init(buildingData: { id: string, level: number }[]) {
        this.buildingsDB = await getAllBuildings();
        buildingData.forEach(building => {
            const buildingToFind = this.buildingsDB.find(b => b.id === building.id);

            if(buildingToFind) this.buildings.push(new Building(
                this,
                buildingToFind,
                building.level
            ))
        })

        return this;
    }

    getBuildingById(id: string) {
        return this.buildings.find(building => building.data.id === id);
    }

    addBuilding(building: Building) {
        const findBuilding = this.buildings.find(b => b.data.id === building.data.id);
        if(!findBuilding) this.buildings.push(building);
        else findBuilding.level++;
    }

    removeBuilding(id: string) {
        this.buildings = this.buildings.filter(building => building.data.id !== id);
    }

    async sync() {
        await updatePlanetBuildings(this.planet._id, this.buildings.map(building => { return { id: building.data.id, level: building.level } }));
    }
}