import { Planet } from '../PlanetManager';
import DBShip from '../../../../types/db/DBShip';
import { getAllShips } from '../../../db/ships';
import Ship from '../../Ship';
import SystemManager from '../SystemManager';

export default abstract class ShipManager {
    ships: Array<Ship> = [];
    shipsDB: Array<DBShip> = [];
    protected _manager: Planet | SystemManager;

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

    abstract get manager(): Planet | SystemManager;

    async init(shipData: { id: string, amount: number }[]) {
        this.shipsDB = await getAllShips();

        for(const ship of shipData) {
            const shipToFind = this.shipsDB.find(s => s.id === ship.id);

            if(shipToFind) this.ships.push(new Ship(
                this,
                shipToFind,
                ship.amount
            ))
        }

        return this;
    }

    getShipById(id: string) {
        return this.ships.find(ship => ship.data.id === id);
    }

    addShips(id: string, amount: number) {
        const findShip = this.ships.find(s => s.data.id === id);
        if(!findShip) { 
            const shipData = this.shipsDB.find(s => s.id === id);
            if(!shipData) return;

            this.ships.push(new Ship(
                this,
                shipData,
                amount
            ));
        }
        else findShip.amount += amount;
    }

    removeShips(id: string, amount: number) {
        const findShip = this.ships.find(s => s.data.id === id);
        if(findShip) {
            findShip.amount -= amount;
            // If no more ships left, remove from array
            if(findShip.amount <= 0) this.ships.splice(this.ships.indexOf(findShip), 1);
        }
    }
}