import { convertMillisecondsToTimeString, convertSecondsToTimeString } from '@/utils/markdown.js';
import { getGroup, renderGroupEveRefLink } from './group';
import type { LocalizedString } from './shared-types';
import { getType, renderTypeEveRefLink } from './type';
import { dataSets, loadModels } from './loadModels';

const sizeMap = {
  1: 'Small',
  2: 'Medium',
  3: 'Large',
  4: 'X-Large',
};

export interface Unit {
  readonly unit_id: number;
  readonly display_name: string;
  readonly description: LocalizedString;
  readonly name: LocalizedString;
}

export function getUnit(unit_id: number) {
  if (!dataSets.loaded) loadModels();
  const unit = dataSets.units[String(unit_id)];
  if (!unit) throw new Error(`Unit ID ${unit_id} not found in reference data`);
  return unit;
}

export function renderUnit(unit: Unit, value: number, locale: string = 'en'): string {
  switch (unit.unit_id) {
    case 108: // inverse percentage
    case 111: // Inverse percentage
      return [(1 - value).toFixed(2), unit.display_name ?? ''].join(' ');
    case 3: // seconds
      return `${convertSecondsToTimeString(value)}`;
    case 101: // milliseconds
      return `${convertMillisecondsToTimeString(value)}`;
    case 117: // size class
      return sizeMap[value] ?? 'Unknown';
    case 141: // hardpoints
      return value + '';
    case 120: // calibration
      return value + ' pts';
    case 116: // typeID
      return getType(value).name[locale] ?? 'Unknown';
    case 10: // m/s
      return `${value} m/s`;
    case 11: // meters per second squared
      return `${value} m/s²`;
    case 9: // cubic meters
      return `${value} m³`;
    case 8: // square meters
      return `${value} m²`;
    case 12: // reciprocal meters
      return `${value} m⁻¹`;
    case 128: // megabits per second
      return `${value} Mbps`;
    case 115: // groupID
      return renderGroupEveRefLink(getGroup(value), locale) ?? 'Unknown';
    default:
      return [value, unit.display_name ?? ''].join(' ');
  }
}

export function isUnitInversePercentage(unit: Unit) {
  return unit.unit_id == 108 || unit.unit_id == 111;
}
