import { CommonModule } from '@angular/common';
import { Component, inject } from '@angular/core';
import { GameService } from '../../../service/game.service';
import { CdkDrag, CdkDragDrop, CdkDragHandle, CdkDropList, moveItemInArray, transferArrayItem } from '@angular/cdk/drag-drop';
import { Planet } from '../../../model/planet.model';
import { ShipConfig } from '../../../model/ships/ship.model';
import { FormsModule } from '@angular/forms';
import { SHIP_DATA } from '../../../model/ships/ship.type';

@Component({
  selector: 'app-buy',
  imports: [CommonModule, CdkDropList, CdkDrag, CdkDragHandle, FormsModule],
  templateUrl: './buy.component.html',
  styleUrl: './buy.component.scss'
})
export class BuyComponent {
  private gameService: GameService = inject(GameService);

  availablePlanets: Planet[] = this.gameService.planets.filter(p => p.hasHarbour);
  selectedPlanets: Planet[] = [];
  config: ShipConfig = {
    ...SHIP_DATA.light,
    planetRoute: []
  }

  config2: ShipConfig = {
    ...SHIP_DATA.medium,
    planetRoute: [],
  }

  config3: ShipConfig = {
    ...SHIP_DATA.heavy,
    planetRoute: []
  }

  selectedModel = '1';

  get selectedShip(): ShipConfig {

    if (this.selectedModel == '1') {
      return this.config;
    } else if (this.selectedModel == '3') {
      return this.config3
    }
    
    return this.config2;
  }

  canAffordShip() {
    return this.gameService.money >= this.config.buyCost;
  }

  buyShip() {
    if (!this.canAffordShip()) return;
    this.gameService.createShip({
      ...this.selectedShip,
      planetRoute: this.selectedPlanets
    })
    this.close();
  }

  close() {
    this.gameService.showBuyShip = false;
  }

  drop(event: CdkDragDrop<Planet[]>) {
    if (event.previousContainer === event.container) {
      moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);
    } else {
      transferArrayItem(
        event.previousContainer.data,
        event.container.data,
        event.previousIndex,
        event.currentIndex,
      );
    }
  }
  
}
