import { SimpleLocalClient } from '../../core/index.js';
import { GoveeBleMapper } from './govee_ble.mapper.js';
import type { IGoveeBleConfig, IGoveeBleSnapshot } from './govee_ble.types.js';
import { goveeBleProfile } from './govee_ble.types.js';

export class GoveeBleClient extends SimpleLocalClient<IGoveeBleConfig> {
  constructor(private readonly configArg: IGoveeBleConfig) {
    super(goveeBleProfile, localRuntimeConfig(configArg));
  }

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

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

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