import { GameMap } from "../game-map";
import { findPath } from "../pathfinding";
import { Tile } from "../tile";
import { Job } from "./base-job";
import { Worker } from "../worker";
import { LumberHut } from "../building/lumber-building";

export class CutTreeJob extends Job {
    constructor(
    map: GameMap,
    worker: Worker,
    private target: Tile,
    private home: LumberHut
  ) {
    super(map, worker);
    this.workDuration = 4; // 4 Sekunden Hackzeit
  }

  start(): void {
    const start = this.map.getTile(Math.floor(this.worker.x), Math.floor(this.worker.y))!;
    const path = findPath(this.map, start, this.target);
    this.worker.setPath(path);
    this.state = 'walking';
  }

  update(dt: number): void {
    switch (this.state) {
      case 'walking':
        this.walk(dt);
        break;

      case 'working':
        this.progress += dt / this.workDuration;
        if (this.progress >= 1) {
          const wood = this.target.harvestWood(1);
          if (wood > 0) {
            this.worker.carrying = wood;

            const homeTile = this.map.getTile(this.home.x, this.home.y)!;
            const start = this.map.getTile(Math.floor(this.worker.x), Math.floor(this.worker.y))!;
            const path = findPath(this.map, start, homeTile);
            this.worker.setPath(path);
            this.state = 'returning';
          } else {
            this.state = 'done';
          }
        }
        break;

      case 'returning':
        if (this.worker.followPath(dt)) {
          this.home.stored['wood'] = (this.home.stored['wood'] ?? 0) + this.worker.carrying;
          this.worker.carrying = 0;
          this.state = 'done';
        }
        break;
      }
      
  }
}