import { Building, BuildingType } from "./building/building";
import { LumberHut } from "./building/lumber-building";
import { StorageBuilding } from "./building/storage.building";
import { GameMap } from "./game-map";
import { ResourceManager, ResourceType } from "./resource-manager";
import { Worker } from "./worker";

export class BuildingSystem {
    private buildings: Building[] = [];

    constructor(private map: GameMap, private res: ResourceManager) {}

    getAll(): Building[] {
        return this.buildings;
    }

    tryPlaceBuilding(x: number, y:number, type: BuildingType): Building | null {
        const tile = this.map.getTile(x, y);
        if (!tile || tile.type == 'water') { return null; }

        const occupied = this.buildings.some(b => b.x == x && b.y == y);
        if (occupied) {
            return null;
        }

        const cost = this.getCost(type);
        if (!this.res.pay(cost)) {
        console.warn('Nicht genug Ressourcen!');
        return null;
        }

        if (type == 'lumberjack') {
          const b = new LumberHut(this.map, x, y, this.buildings);
          this.buildings.push(b);
          const w = new Worker(x, y);
          b.assignWorker(w);
          return b;
        } else if (type == 'storage') {
          const b = new StorageBuilding(this.map, x, y, this.buildings);
          this.buildings.push(b)
          const w = new Worker(x,y);
          b.assignWorker(w);
          return b;
        }
        return null;
    }
    

    private getCost(type: BuildingType): Partial<Record<ResourceType, number>> {
    switch (type) {
      case 'house': return { wood: 5, stone: 2 };
      case 'lumberjack': return { wood: 3, stone: 1 };
      case 'quarry': return { wood: 2, stone: 3 };
      default: return {};
    }
  }

  update(dt: number) {
    for (const b of this.buildings) {
      b.update(dt)
    }
  }
}