import DBStructure from '../../../types/db/DBStructure';
import { getAllStructures } from '../../db/structures';
import { updateSystemStructures } from '../../db/systems';
import Structure from '../Structure';
import SystemManager from './SystemManager';

export default class StructureManager {
    structures: Array<Structure> = [];
    structuresDB: Array<DBStructure> = []
    system: SystemManager;

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

    async init(structureData: { id: string, level: number }[]) {
        this.structuresDB = await getAllStructures();
        structureData.forEach(structure => {
            const structureToFind = this.structuresDB.find(s => s.id === structure.id);

            if(structureToFind) this.structures.push(new Structure(
                this,
                structureToFind,
                structure.level
            ))
        })

        return this;
    }

    getStructureById(id: string) {
        return this.structures.find(structure => structure.data.id === id);
    }

    addStructure(structure: Structure) {
        const findStructure = this.structures.find(s => s.data.id === structure.data.id);
        if(!findStructure) this.structures.push(structure);
        else findStructure.level++;
    }

    removeStructure(id: string) {
        this.structures = this.structures.filter(structure => structure.data.id !== id);
    }

    async sync() {
        await updateSystemStructures(this.system.data._id, this.structures.map(structure => { return { id: structure.data.id, level: structure.level } }));
    }
}