// The server owns ships, hulls and loose pieces; this is the shape it reports,
// plus the local-to-world transform every client needs to draw a hull.
export type Kind = 'triangle' | 'square' | 'circle' | 'star';

// Piece position is local to the ship: the graph is rigid, so only the hull moves.
export type Piece = {
  id: number;
  kind: Kind;
  lx: number;
  ly: number;
  parent: number;
  hp: number;
  maxhp: number;
  tier: number;
};
export type Loose = {
  id: number;
  kind: Kind;
  x: number;
  y: number;
  h: number;
  hp: number;
  maxhp: number;
  tier: number;
};
export type Ore = { id: number; x: number; y: number; h: number; towed: number };
export type Shot = { id: number; x: number; y: number; h: number };
export type Body = { id: number; kind: 'star' | 'shipyard' | 'barren'; r: number; x: number; y: number };
// The centre a system's bodies circle: one mark on the galaxy map.
export type System = { id: number; x: number; y: number };

export type Ship = {
  id: number;
  name: string;
  x: number;
  y: number;
  h: number;
  tx: number; // where it is flying to, so the marker can show the order
  ty: number;
  order: boolean; // that order is still pending, so the marker is due
  fuel: number; // what is in the tank
  fuelmax: number; // capacity, summed from the hull
  side: string; // police or rogue for a server hull, empty for a player
  foe: number; // the ship this one is chasing, 0 = nobody
  target: number; // piece of that ship its guns are pointed at, 0 = the nearest
  ai: boolean; // a server-run hull, so it draws in its own colour
  pieces: Piece[];
};

// The same rule the server shoots by, so the rim on a hull can never say hostile
// while the guns say neutral: the rogue faction is at war with everything else on
// sight, and anyone else is only at war once one of the two has declared it.
export const hostile = (a?: Ship, b?: Ship): boolean => {
  if (!a || !b || a.id === b.id) return false;
  if (a.side === 'rogue' || b.side === 'rogue') return a.side !== b.side;
  return a.foe === b.id || b.foe === a.id;
};

export function toWorld(s: Ship, p: Piece): { x: number; y: number } {
  const c = Math.cos(s.h);
  const n = Math.sin(s.h);
  return { x: s.x + p.lx * c - p.ly * n, y: s.y + p.lx * n + p.ly * c };
}
