import { SimpleLocalIntegration, SimpleLocalRuntime, type IIntegrationEvent, type IIntegrationRuntime, type IIntegrationSetupContext } from '../../core/index.js';
import { PilightClient } from './pilight.classes.client.js';
import { PilightConfigFlow } from './pilight.classes.configflow.js';
import { createPilightDiscoveryDescriptor } from './pilight.discovery.js';
import { PilightMapper } from './pilight.mapper.js';
import type { IPilightConfig } from './pilight.types.js';
import { pilightDomain, pilightProfile } from './pilight.types.js';

export class PilightIntegration extends SimpleLocalIntegration<IPilightConfig> {
  public readonly domain = pilightDomain;
  public readonly discoveryDescriptor = createPilightDiscoveryDescriptor();
  public readonly configFlow = new PilightConfigFlow();

  constructor() {
    super(pilightProfile);
  }

  public override async setup(configArg: IPilightConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new PilightRuntime(new PilightClient(configArg));
  }
}

export class HomeAssistantPilightIntegration extends PilightIntegration {}

class PilightRuntime extends SimpleLocalRuntime<IPilightConfig> {
  constructor(private readonly pilightClient: PilightClient) {
    super(pilightProfile, pilightClient);
  }

  public async subscribe(handlerArg: (eventArg: IIntegrationEvent) => void): Promise<() => Promise<void>> {
    const unsubscribe = await this.pilightClient.subscribe((messageArg) => handlerArg(PilightMapper.toIntegrationEvent(messageArg)));
    return async () => unsubscribe();
  }
}
