import URDFLoader from './URDFLoader.js';

export default
class ExtendedURDFLoader extends URDFLoader {
  constructor(manager) {
    super(manager);
    this.transmissionMap = {};
  }

  parseTransmissions(xml) {
    const transmissions = xml.querySelectorAll('transmission');
    this.transmissionMap = {};

    transmissions.forEach(trans => {
      const jointName = trans.querySelector('joint')?.getAttribute('name');
      const actuator = trans.querySelector('actuator');
      const reduction = parseFloat(actuator?.querySelector('mechanicalReduction')?.textContent ?? '1');
      const actuatorName = actuator?.getAttribute('name') ?? null;
      const encoderMax = parseInt(actuator?.querySelector('encoderTicks')?.textContent ?? '4096');
      const encoderValidMin = parseInt(actuator?.querySelector('encoderValidMin')?.textContent ?? '0');
      const encoderValidMax = parseInt(actuator?.querySelector('encoderValidMax')?.textContent ?? '4095');

      if (jointName) {
        this.transmissionMap[jointName] = {
          gearRatio: reduction,
          actuatorName,
          encoderMax,
          encoderValidMin,
          encoderValidMax
        };
      }
    });
  }

  async loadFromString(urdfText, options = {}) {
    const xml = new DOMParser().parseFromString(urdfText, 'application/xml');
    const parserError = xml.querySelector('parsererror');
    if (parserError) {
      console.error('❌ XML parser error:', parserError.textContent);
      throw new Error('Invalid URDF XML: ' + parserError.textContent);
    }

    this.parseTransmissions(xml);

    const robot = this.parse(xml); // ✅ Use inherited parse() directly

    for (const jointName in robot.joints) {
      if (this.transmissionMap[jointName]) {
        robot.joints[jointName].transmission = this.transmissionMap[jointName];
      }
    }

    return robot;
  }
}
