import { SimpleLocalClient } from '../../core/index.js';
import { MqttJsonMapper } from './mqtt_json.mapper.js';
import type { IMqttJsonConfig, IMqttJsonSnapshot } from './mqtt_json.types.js';
import { mqttJsonLiveUnsupportedReason, mqttJsonProfile } from './mqtt_json.types.js';

export class MqttJsonClient extends SimpleLocalClient<IMqttJsonConfig> {
  constructor(private readonly configArg: IMqttJsonConfig) {
    super(mqttJsonProfile, safeSnapshotConfig(configArg));
  }

  public async getSnapshot(forceRefreshArg = false): Promise<IMqttJsonSnapshot> {
    if (!hasSafeSnapshotSource(this.configArg)) {
      return MqttJsonMapper.toSnapshot({ config: this.configArg, online: false, source: 'runtime', error: mqttJsonLiveUnsupportedReason }) as IMqttJsonSnapshot;
    }

    return await super.getSnapshot(forceRefreshArg) as IMqttJsonSnapshot;
  }
}

const hasSafeSnapshotSource = (configArg: IMqttJsonConfig): boolean => Boolean(
  configArg.client
  || configArg.snapshotProvider
  || configArg.snapshot
  || configArg.rawData !== undefined
  || configArg.rawText !== undefined
  || configArg.entities?.length,
);

const safeSnapshotConfig = (configArg: IMqttJsonConfig): IMqttJsonConfig => ({
  ...configArg,
  host: undefined,
  port: undefined,
  path: undefined,
  transport: configArg.transport === 'snapshot' ? 'snapshot' : undefined,
  tcpCommand: undefined,
  url: undefined,
});
