import { type VueLike, unwrap_vuelike } from "../helpers";
import type { DoorSaved } from "../model";
import { Rectangle } from "./rectangle";
import { Vector2D } from "./vector2d";

export class Door {
  public static readonly MIN_DAY = 1;

  private _day = Door.MIN_DAY;
  public position: Rectangle;

  constructor(position: VueLike<Rectangle>);
  constructor(position: VueLike<Rectangle>, day: number);
  constructor(position: VueLike<Rectangle>, day = Door.MIN_DAY) {
    this.day = day;
    this.position = unwrap_vuelike(position);
  }

  public get day(): number {
    return this._day;
  }

  public set day(value: number | string) {
    // integer coercion
    let day = Number(value);

    day =
      !Number.isNaN(day) && Number.isFinite(day)
        ? Math.trunc(day)
        : Door.MIN_DAY;

    this._day = Math.max(day, Door.MIN_DAY);
  }

  public static load(serialized: DoorSaved): Door {
    return new Door(
      new Rectangle(
        new Vector2D(serialized.x1, serialized.y1),
        new Vector2D(serialized.x2, serialized.y2),
      ),
      serialized.day,
    );
  }

  public save(): DoorSaved {
    return {
      day: this.day,
      x1: this.position.origin.x,
      y1: this.position.origin.y,
      x2: this.position.corner.x,
      y2: this.position.corner.y,
    };
  }
}
