import { EventEmitter } from "@angular/core";
import { interval } from "rxjs";
import { Planet } from "../model/planet.model";
import { PlanetStatus } from "./planet-status.ui";
import { GameService } from "../service/game.service";

export class PlanetUi extends Phaser.Physics.Arcade.Sprite {

  public leftClick: EventEmitter<PlanetUi> = new EventEmitter();
  public rightClick: EventEmitter<PlanetUi> = new EventEmitter();
  public model: Planet;
  private status: PlanetStatus | undefined;
  private harbourImage!: any;

  private updateInterval = interval(1000)
  
  constructor(scene: Phaser.Scene, x: number, y: number, texture: string, config: any, gameService: GameService) {
    super(scene, x, y, texture);
    // this.setDisplaySize(200, 200);
    

    this.model = new Planet(config, gameService);

    scene.add.existing(this);
    this.setInteractive({ useHandCursor: true });

    this.leftClick.emit();


    this.on('pointerdown', (pointer: Phaser.Input.Pointer) => {
      if (pointer.button == Phaser.Input.MOUSE_DOWN) {
        this.leftClick.emit(this)
      } else if (pointer.button == Phaser.Input.MOUSE_UP) {
        this.rightClick.emit(this);
      }
    });



    this.status = new PlanetStatus(scene, this, () => this.model.population, () => this.model.isGrowing ? 'growing' : 'shrinking', () => this.model.getCriticalGoods())

    this.updateInterval.subscribe(() => this.update())


    this.harbourImage = this.scene.add.image(this.getWorldPoint().x, this.getWorldPoint().y, 'harbour')
    this.harbourImage.setDisplaySize(164, 256);
    this.harbourImage.setVisible(false);

    console.log(this.height)

    // this.setScale(0.5)

    // this.setInteractive(new Phaser.Geom.Circle(x, y, 200), Phaser.Geom.Circle.Contains);
  }


  override update(...args: any[]): void {

    const offers = this.model.offeredGoods;
    

    let text = `${this.model.name}`;
    if (offers.length > 0) {
      text += `\nAngebot: ${offers[0].type}: ${offers[0].amount.toFixed(2)}`
    }


    const request = this.model.requestedGoods;
    if (request.length > 0) {
      text += `\nNachgefragt: ${request[0].type}: ${request[0].amount.toFixed(2)}`
    }

    this.status?.update();
    this.harbourImage.setVisible(this.model.hasHarbour)
    
  }

}