import type * as shxInterfaces from '@smarthome.exchange/interfaces';
import { BaseIntegration } from '../../core/classes.baseintegration.js';
import type { IIntegrationEntity, IIntegrationEvent, IIntegrationRuntime, IIntegrationSetupContext, IServiceCallRequest, IServiceCallResult } from '../../core/types.js';
import { OpenRGBClient } from './openrgb.classes.client.js';
import { OpenRGBConfigFlow } from './openrgb.classes.configflow.js';
import { createOpenRGBDiscoveryDescriptor } from './openrgb.discovery.js';
import { OpenRGBMapper } from './openrgb.mapper.js';
import type { IOpenRGBConfig } from './openrgb.types.js';

export class OpenRGBIntegration extends BaseIntegration<IOpenRGBConfig> {
  public readonly domain = 'openrgb';
  public readonly displayName = 'OpenRGB';
  public readonly status = 'control-runtime' as const;
  public readonly discoveryDescriptor = createOpenRGBDiscoveryDescriptor();
  public readonly configFlow = new OpenRGBConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/openrgb',
    upstreamDomain: 'openrgb',
    integrationType: 'hub',
    iotClass: 'local_polling',
    qualityScale: 'silver',
    requirements: ['openrgb-python==0.3.6'],
    dependencies: [] as string[],
    afterDependencies: [] as string[],
    codeowners: ['@felipecrs'],
    documentation: 'https://www.home-assistant.io/integrations/openrgb',
    protocolDocumentation: 'https://gitlab.com/CalcProgrammer1/OpenRGB#openrgb-sdk',
    defaultPort: 6742,
  };

  public async setup(configArg: IOpenRGBConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new OpenRGBRuntime(new OpenRGBClient(configArg));
  }

  public async destroy(): Promise<void> {}
}

export class HomeAssistantOpenrgbIntegration extends OpenRGBIntegration {}

class OpenRGBRuntime implements IIntegrationRuntime {
  public domain = 'openrgb';

  constructor(private readonly client: OpenRGBClient) {}

  public async devices(): Promise<shxInterfaces.data.IDeviceDefinition[]> {
    return OpenRGBMapper.toDevices(await this.client.getSnapshot());
  }

  public async entities(): Promise<IIntegrationEntity[]> {
    return OpenRGBMapper.toEntities(await this.client.getSnapshot());
  }

  public async subscribe(handlerArg: (eventArg: IIntegrationEvent) => void): Promise<() => Promise<void>> {
    const unsubscribe = this.client.onEvent((eventArg) => handlerArg(OpenRGBMapper.toIntegrationEvent(eventArg)));
    await this.client.getSnapshot();
    return async () => unsubscribe();
  }

  public async callService(requestArg: IServiceCallRequest): Promise<IServiceCallResult> {
    const snapshot = await this.client.getSnapshot();
    const command = OpenRGBMapper.commandForService(snapshot, requestArg);
    if (!command) {
      return { success: false, error: `Unsupported OpenRGB service mapping: ${requestArg.domain}.${requestArg.service}` };
    }
    return this.client.sendCommand(command);
  }

  public async destroy(): Promise<void> {
    await this.client.destroy();
  }
}
