import { Planet, TradeInstance } from "../planet.model"

export class TradeRoute {
  private route: ITradePlanet[] = [];

  private target!: ITradePlanet;

  constructor(route: Planet[]) {
    const r: any[] = route.map(r => { return {target: r, next: null }})
    if (route.length < 2) { return;}

    for (let i = 1; i < route.length; i++) {
      r[i-1].next = r[i];
    }
    r[r.length - 1].next = r[0];
    this.target = r[0];
    this.route = r;
  }

  get nextPlanetName(): string {
    return this.target?.target.name ?? '';
  }

  routePointReached() {
    if (!this.target) { return; }
    this.target = this.target.next;
  }


  /**
   * Returns an array of trade demands from all planets in the route except the current target
   * @returns Array of TradeInstance representing goods demanded by planets in the route
   */
  getTradeRouteDemands(): TradeInstance[] {
    // Return empty array if route or target is not initialized
    if (!this.route || !this.target)  { return[] }
    const demands = [];

    const max = this.route.length;
    let target = this.target;
    // Iterate through all planets in route except current target
    for (let i = 1; i < max; i++) {
      target = target.next;
      // Add all requested goods from each planet to demands array
      demands.push(...target.target.requestedGoods);
    }
    return demands;
  }

  get planetNames(): string[] {
    return this.route.map(r => r.target.name);
  }
}

interface ITradePlanet {
  target: Planet;
  next: ITradePlanet;
}