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 { UnifiClient } from './unifi.classes.client.js';
import { UnifiConfigFlow } from './unifi.classes.configflow.js';
import { createUnifiDiscoveryDescriptor } from './unifi.discovery.js';
import { UnifiMapper } from './unifi.mapper.js';
import type { IUnifiConfig } from './unifi.types.js';

export class UnifiIntegration extends BaseIntegration<IUnifiConfig> {
  public readonly domain = 'unifi';
  public readonly displayName = 'UniFi Network';
  public readonly status = 'control-runtime' as const;
  public readonly discoveryDescriptor = createUnifiDiscoveryDescriptor();
  public readonly configFlow = new UnifiConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/unifi',
    upstreamDomain: 'unifi',
    integrationType: 'hub',
    iotClass: 'local_push',
    qualityScale: 'silver',
    requirements: ['aiounifi==90'],
    dependencies: ['unifi_discovery'],
    afterDependencies: [] as string[],
    codeowners: ['@Kane610'],
    documentation: 'https://www.home-assistant.io/integrations/unifi',
    protocolSource: 'aiounifi local controller API: /api/login, /api/s/{site}/stat/sta, /rest/user, /stat/device, /rest/wlanconf',
  };

  public async setup(configArg: IUnifiConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new UnifiRuntime(new UnifiClient(configArg));
  }

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

export class HomeAssistantUnifiIntegration extends UnifiIntegration {}

class UnifiRuntime implements IIntegrationRuntime {
  public domain = 'unifi';

  constructor(private readonly client: UnifiClient) {}

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

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

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

  public async callService(requestArg: IServiceCallRequest): Promise<IServiceCallResult> {
    const snapshot = await this.client.getSnapshot();
    const command = UnifiMapper.commandForService(snapshot, requestArg);
    if (!command) {
      return { success: false, error: `UniFi service ${requestArg.domain}.${requestArg.service} has no native mapping for the target.` };
    }
    const result = await this.client.sendCommand(command);
    return { success: result.success, error: result.error, data: result.data };
  }

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