import { SimpleLocalClient } from '../../core/index.js';
import { HomeeMapper } from './homee.mapper.js';
import type { IHomeeConfig, IHomeeSnapshot } from './homee.types.js';
import { homeeProfile } from './homee.types.js';

export class HomeeClient extends SimpleLocalClient<IHomeeConfig> {
  constructor(private readonly configArg: IHomeeConfig) {
    super(homeeProfile, configArg);
  }

  public async getSnapshot(forceRefreshArg = false): Promise<IHomeeSnapshot> {
    if (this.configArg.rawData !== undefined || this.configArg.rawText !== undefined || this.configArg.entities?.length) {
      return HomeeMapper.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 HomeeMapper.toSnapshot({ config: { ...this.configArg, snapshot }, online: snapshot.online, source: snapshot.source, error: snapshot.error });
    }

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