import { GameMap } from "../game-map";
import { findPath } from "../pathfinding";
import { Job } from "./base-job";
import { Worker } from "../worker";
import { ProductionBuilding } from "../building/production-building";
import { ResourceType } from "../resource-manager";
import { ResouceBuilding } from "../building/resource-building";

export class CollectMaterialJob extends Job {
  private good: ResourceType | null = null;
    
  constructor(
    map: GameMap,
    worker: Worker,
    private target: ProductionBuilding,
    private home: ResouceBuilding
    ) {
    super(map, worker);
    this.workDuration = 1; // 4 Sekunden Hackzeit
  }


  override start(): void {
    const start = this.map.getTile(Math.floor(this.worker.x), Math.floor(this.worker.y))!;
    const target = this.map.getTile(this.target.x, this.target.y)!;
    const path = findPath(this.map, start, target);
    this.worker.setPath(path);
    this.state = 'walking';
  }
  override update(dt: number): void {
    switch (this.state) {
      case 'walking':
        this.walk(dt);
        break;
      case 'working': 
        this.progress += dt / this.workDuration;
        if (this.progress < 1) {
          break;
        }
        this.good = this.target.collectGoods();
        if (this.good == null) {
          this.state = 'done';
          break;
        }

        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';
        break;

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