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

@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 = {
    name: 'Pioneer-01',
    acceleration: 428,
    cargoSize: 25,
    cost: 0.6,
    loadingSpeed: 15,
    maxSpeed: 300,
    planetRoute: [],
    buyCost: 3000,
    desciption: 'Ein kleines, schnelles Schiff. Es hat wenig Platz für Ladung, lädt aber schnell und ist sehr wendig.',
    texture: 'swift-hauler'
  }

  config2: ShipConfig = {
    name: 'Colony Carrier',
    acceleration: 63,
    cargoSize: 70,
    cost: 1.6,
    loadingSpeed: 20,
    maxSpeed: 200,
    planetRoute: [],
    buyCost: 8000,
    desciption: 'Eine größere Version von der Pioneer-01. Der größere Frachtraum geht zu Lasten der Beschleunigung und Maximalgeschwindigkeit.',
    texture: 'colony-carrier'
  }

  config3: ShipConfig = {
    name: 'Industrial Tanker',
    acceleration: 8,
    cargoSize: 300,
    cost: 3.8,
    loadingSpeed: 11,
    maxSpeed: 600,
    planetRoute: [],
    buyCost: 14000,
    desciption: 'Ein großes behäbiges Schiff. Es wird durchaus schnell, beschleunigt aber sehr langsam und erreicht die Spitzengeschwindigkeit nur selten.',
    texture: 'industrial-tanker'
  }

  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,
      );
    }
  }
  
}
