import { SimpleLocalClient } from '../../core/index.js';
import { MqttRoomMapper } from './mqtt_room.mapper.js';
import type { IMqttRoomConfig, IMqttRoomSnapshot } from './mqtt_room.types.js';
import { mqttRoomLiveUnsupportedReason, mqttRoomProfile } from './mqtt_room.types.js';

export class MqttRoomClient extends SimpleLocalClient<IMqttRoomConfig> {
  constructor(private readonly configArg: IMqttRoomConfig) {
    super(mqttRoomProfile, safeSnapshotConfig(configArg));
  }

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

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

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

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