import { SimpleLocalClient } from '../../core/index.js';
import { GpsdMapper } from './gpsd.mapper.js';
import type { IGpsdConfig, IGpsdSnapshot } from './gpsd.types.js';
import { gpsdProfile } from './gpsd.types.js';

export class GpsdClient extends SimpleLocalClient<IGpsdConfig> {
  constructor(private readonly configArg: IGpsdConfig) {
    super(gpsdProfile, localRuntimeConfig(configArg));
  }

  public async getSnapshot(forceRefreshArg = false): Promise<IGpsdSnapshot> {
    const snapshot = await super.getSnapshot(forceRefreshArg);
    if (snapshot.rawData === undefined && snapshot.entities.length) {
      return GpsdMapper.toSnapshot({ config: { ...this.configArg, snapshot }, online: snapshot.online, source: snapshot.source, error: snapshot.error });
    }

    return GpsdMapper.toSnapshot({ config: this.configArg, rawData: snapshot.rawData, online: snapshot.online, source: snapshot.source, error: snapshot.error });
  }
}

const localRuntimeConfig = (configArg: IGpsdConfig): IGpsdConfig => configArg.rawData !== undefined || configArg.entities?.length || configArg.snapshot ? { ...configArg, host: undefined, path: undefined, transport: 'snapshot' } : configArg;
