import { SimpleLocalClient } from '../../core/index.js';
import { GraphiteMapper } from './graphite.mapper.js';
import type { IGraphiteConfig, IGraphiteSnapshot } from './graphite.types.js';
import { graphiteProfile } from './graphite.types.js';

export class GraphiteClient extends SimpleLocalClient<IGraphiteConfig> {
  constructor(private readonly configArg: IGraphiteConfig) {
    super(graphiteProfile, localRuntimeConfig(configArg));
  }

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

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

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