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 { DevoloHomeNetworkClient } from './devolo_home_network.classes.client.js';
import { DevoloHomeNetworkConfigFlow } from './devolo_home_network.classes.configflow.js';
import { createDevoloHomeNetworkDiscoveryDescriptor } from './devolo_home_network.discovery.js';
import { DevoloHomeNetworkMapper } from './devolo_home_network.mapper.js';
import type { IDevoloConfig } from './devolo_home_network.types.js';
import { devoloHomeNetworkDomain } from './devolo_home_network.types.js';

export class DevoloHomeNetworkIntegration extends BaseIntegration<IDevoloConfig> {
  public readonly domain = devoloHomeNetworkDomain;
  public readonly displayName = 'devolo Home Network';
  public readonly status = 'control-runtime' as const;
  public readonly discoveryDescriptor = createDevoloHomeNetworkDiscoveryDescriptor();
  public readonly configFlow = new DevoloHomeNetworkConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/devolo_home_network',
    upstreamDomain: devoloHomeNetworkDomain,
    integrationType: 'device',
    iotClass: 'local_polling',
    qualityScale: 'silver',
    requirements: ['devolo-plc-api==1.5.1'],
    dependencies: ['zeroconf'],
    afterDependencies: [] as string[],
    codeowners: ['@2Fake', '@Shutgun'],
    documentation: 'https://www.home-assistant.io/integrations/devolo_home_network',
    mdnsType: '_dvl-deviceapi._tcp.local.',
    liveHttpImplemented: false,
  };

  public async setup(configArg: IDevoloConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new DevoloHomeNetworkRuntime(new DevoloHomeNetworkClient(configArg));
  }

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

export class HomeAssistantDevoloHomeNetworkIntegration extends DevoloHomeNetworkIntegration {}

class DevoloHomeNetworkRuntime implements IIntegrationRuntime {
  public domain = devoloHomeNetworkDomain;

  constructor(private readonly client: DevoloHomeNetworkClient) {}

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

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

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

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

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