import { SimpleLocalClient } from '../../core/index.js';
import { FibaroMapper } from './fibaro.mapper.js';
import type { IFibaroConfig, IFibaroSnapshot } from './fibaro.types.js';
import { fibaroProfile } from './fibaro.types.js';

export class FibaroClient extends SimpleLocalClient<IFibaroConfig> {
  constructor(private readonly configArg: IFibaroConfig) {
    super(fibaroProfile, configArg);
  }

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

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

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