import { GameMap } from "../game-map";
import { CutTreeJob } from "../job/cut-tree.job";
import { ResourceType } from "../resource-manager";
import { Tile } from "../tile";
import { Worker } from "../worker";
import { Building } from "./building";
import { ProductionBuilding } from "./production-building";




export class LumberHut extends ProductionBuilding {
  constructor(map: GameMap, x: number, y: number, buildings: Building[]) {
    super(map, x, y, buildings);
    this.type = 'lumberjack';
  }

  override update(dt: number): void {
    super.update(dt);
    if (!this.assignedWorker) { return; }
    if (!this.assignedWorker.idle) { return; }
    if (this.storageFull) { return; }

    const forest = this.findNearestResourceNode();
    if (!forest) { return; }

    this.assignedWorker.setJob(new CutTreeJob(this.map, this.assignedWorker, forest, this))

  }

  findNearestResourceNode(): Tile | null {
    let best: Tile | null = null;
    let bestDist = Infinity;
    for (let dy = -10; dy <= 10; dy++) {
      for (let dx = -10; dx <= 10; dx++) {
        const tile = this.map.getTile(this.x + dx, this.y + dy);
        if (!tile || tile.type !== 'forest') continue;
        const dist = dx * dx + dy * dy;
        if (dist < bestDist) {
          bestDist = dist;
          best = tile;
        }
      }
    }
    return best;
  }
  
  assignWorker(worker: Worker): void {
    this.assignedWorker = worker;
  }

  collectGoods(): ResourceType | null {
    if (this.stored.wood && this.stored.wood > 0) {
      this.stored.wood -= 1;
      return "wood";
    }
    return null;
  }
}

