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 { TplinkClient } from './tplink.classes.client.js';
import { TplinkConfigFlow } from './tplink.classes.configflow.js';
import { createTplinkDiscoveryDescriptor } from './tplink.discovery.js';
import { TplinkMapper } from './tplink.mapper.js';
import type { ITplinkConfig } from './tplink.types.js';

export class TplinkIntegration extends BaseIntegration<ITplinkConfig> {
  public readonly domain = 'tplink';
  public readonly displayName = 'TP-Link Smart Home';
  public readonly status = 'control-runtime' as const;
  public readonly discoveryDescriptor = createTplinkDiscoveryDescriptor();
  public readonly configFlow = new TplinkConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/tplink',
    upstreamDomain: 'tplink',
    documentation: 'https://www.home-assistant.io/integrations/tplink',
    integrationType: 'device',
    iotClass: 'local_polling',
    qualityScale: 'platinum',
    requirements: ['python-kasa[speedups]==0.10.2'],
    dependencies: ['network', 'ffmpeg', 'stream'],
    afterDependencies: [] as string[],
    codeowners: ['@rytilahti', '@bdraco', '@sdb9696'],
    dhcpDiscoveryPorts: [9999, 20002],
    liveLocalWritesImplemented: false,
  };

  public async setup(configArg: ITplinkConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new TplinkRuntime(new TplinkClient(configArg));
  }

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

export class HomeAssistantTplinkIntegration extends TplinkIntegration {}

class TplinkRuntime implements IIntegrationRuntime {
  public domain = 'tplink';

  constructor(private readonly client: TplinkClient) {}

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

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

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

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

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