import type { CoordinateKey, Region, RegionWithCoords, Updateable } from '@map/types';
import { action, computed, makeObservable, observable } from 'mobx';

export class MapRegion {
  public readonly x: number;
  public readonly y: number;

  public readonly id: number;

  @observable ownerId: number;
  @observable itemId: number;
  @observable updateId: number;
  @observable properties: number;
  @observable hash: number;

  @observable selected = false;

  constructor(region: RegionWithCoords) {
    this.x = region.x;
    this.y = region.y;

    this.id = region.id;
    this.ownerId = region.ownerId ?? 0;
    this.itemId = region.itemId ?? 0;
    this.updateId = region.updateId ?? 0;
    this.properties = region.properties ?? 0;
    this.hash = region.hash ?? 0;

    makeObservable(this);
  }

  @action
  update(region: Partial<Region> & Updateable) {
    const { ownerId, itemId, updateId, properties, hash } = region;

    console.log(region);

    this.ownerId = typeof ownerId !== 'undefined' ? ownerId : this.ownerId;
    this.itemId = typeof itemId !== 'undefined' ? itemId : this.itemId;
    this.updateId = typeof updateId !== 'undefined' ? updateId : this.updateId;
    this.properties = typeof properties !== 'undefined' ? properties : this.properties;
    this.hash = typeof hash !== 'undefined' ? hash : this.hash;
  }

  @action
  toggle() {
    this.selected = !this.selected;
  }

  @computed
  get key(): CoordinateKey {
    return `${this.x}_${this.y}`;
  }

  @computed
  get isSelected() {
    return (this.properties & (1 << 2)) === 1 << 2;
  }
}
