import { SimpleLocalClient } from '../../core/index.js';
import { GreeMapper } from './gree.mapper.js';
import type { IGreeConfig, IGreeSnapshot } from './gree.types.js';
import { greeProfile } from './gree.types.js';

export class GreeClient extends SimpleLocalClient<IGreeConfig> {
  constructor(private readonly configArg: IGreeConfig) {
    super(greeProfile, localRuntimeConfig(configArg));
  }

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

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

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