import { SimpleLocalClient } from '../../core/index.js';
import { HeatmiserMapper } from './heatmiser.mapper.js';
import type { IHeatmiserConfig, IHeatmiserSnapshot } from './heatmiser.types.js';
import { heatmiserProfile } from './heatmiser.types.js';

export class HeatmiserClient extends SimpleLocalClient<IHeatmiserConfig> {
  constructor(private readonly configArg: IHeatmiserConfig) {
    super(heatmiserProfile, configArg);
  }

  public async getSnapshot(forceRefreshArg = false): Promise<IHeatmiserSnapshot> {
    if (!this.configArg.client && !this.configArg.snapshotProvider && (this.configArg.snapshot || this.configArg.rawData !== undefined || this.configArg.rawText !== undefined || this.configArg.entities?.length)) {
      return HeatmiserMapper.toSnapshot({
        config: this.configArg,
        rawData: this.configArg.snapshot ?? this.configArg.rawData ?? this.configArg.rawText,
        online: this.configArg.online ?? true,
        source: this.configArg.snapshot ? 'snapshot' : 'manual',
      });
    }

    const snapshot = await super.getSnapshot(forceRefreshArg);
    if (snapshot.rawData === undefined && snapshot.entities.length) {
      return HeatmiserMapper.toSnapshot({ config: { ...this.configArg, snapshot }, online: snapshot.online, source: snapshot.source, error: snapshot.error });
    }

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