import { Planet } from '../PlanetManager';
import SystemManager from '../SystemManager';
import Defense from '../../Defense';
import DBDefenses from '../../../../types/db/DBDefenses';
import { getAllDefenses } from '../../../db/defenses';

export default abstract class DefenseManager {
    defenses: Array<Defense> = [];
    defensesDB: Array<DBDefenses> = [];
    protected _manager: Planet | SystemManager;

    constructor(manager: Planet | SystemManager) {
        this._manager = manager;
    }
    
    abstract sync(): Promise<void>;

    abstract get manager(): Planet | SystemManager;

    async init(defenseData: { id: string, amount: number }[]) {
        this.defensesDB = await getAllDefenses();

        for(const def of defenseData) {
            const defToFind = this.defensesDB.find(d => d.id === def.id);

            if(defToFind) this.defenses.push(new Defense(
                this,
                defToFind,
                def.amount
            ))
        }

        return this;
    }

    getDefenseById(id: string) {
        return this.defenses.find(def => def.data.id === id);
    }

    addDefenses(id: string, amount: number) {
        const findDef = this.defenses.find(d => d.data.id === id);
        if(!findDef) { 
            const defData = this.defensesDB.find(d => d.id === id);
            if(!defData) return;

            this.defenses.push(new Defense(
                this,
                defData,
                amount
            ));
        }
        else findDef.amount += amount;
    }

    removeDefenses(id: string, amount: number) {
        const findDef = this.defenses.find(d => d.data.id === id);
        if(findDef) {
            findDef.amount -= amount;
            if(findDef.amount <= 0) this.defenses.splice(this.defenses.indexOf(findDef), 1);
        }
    }
}