import type * as shxInterfaces from '@smarthome.exchange/interfaces';
import { BaseIntegration } from '../../core/classes.baseintegration.js';
import type { IIntegrationEntity, IIntegrationRuntime, IIntegrationSetupContext, IServiceCallRequest, IServiceCallResult } from '../../core/types.js';
import { DlnaDmrClient } from './dlna_dmr.classes.client.js';
import { DlnaDmrConfigFlow } from './dlna_dmr.classes.configflow.js';
import { createDlnaDmrDiscoveryDescriptor } from './dlna_dmr.discovery.js';
import { DlnaDmrMapper } from './dlna_dmr.mapper.js';
import type { IDlnaDmrConfig } from './dlna_dmr.types.js';

export class DlnaDmrIntegration extends BaseIntegration<IDlnaDmrConfig> {
  public readonly domain = 'dlna_dmr';
  public readonly displayName = 'DLNA Digital Media Renderer';
  public readonly status = 'control-runtime' as const;
  public readonly discoveryDescriptor = createDlnaDmrDiscoveryDescriptor();
  public readonly configFlow = new DlnaDmrConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/dlna_dmr',
    upstreamDomain: 'dlna_dmr',
    integrationType: 'device',
    iotClass: 'local_push',
    requirements: ['async-upnp-client==0.46.2', 'getmac==0.9.5'],
    dependencies: ['ssdp'],
    afterDependencies: ['media_source'],
    documentation: 'https://www.home-assistant.io/integrations/dlna_dmr',
    codeowners: ['@chishm'],
  };

  public async setup(configArg: IDlnaDmrConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new DlnaDmrRuntime(new DlnaDmrClient(configArg));
  }

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

export class HomeAssistantDlnaDmrIntegration extends DlnaDmrIntegration {}

class DlnaDmrRuntime implements IIntegrationRuntime {
  public domain = 'dlna_dmr';

  constructor(private readonly client: DlnaDmrClient) {}

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

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

  public async callService(requestArg: IServiceCallRequest): Promise<IServiceCallResult> {
    if (requestArg.domain !== 'media_player') {
      return { success: false, error: `Unsupported DLNA DMR service domain: ${requestArg.domain}` };
    }

    if (requestArg.service === 'play' || requestArg.service === 'media_play') {
      await this.client.play();
      return { success: true };
    }

    if (requestArg.service === 'pause' || requestArg.service === 'media_pause') {
      await this.client.pause();
      return { success: true };
    }

    if (requestArg.service === 'stop' || requestArg.service === 'media_stop') {
      await this.client.stop();
      return { success: true };
    }

    if (requestArg.service === 'volume_set' || requestArg.service === 'set_volume' || requestArg.service === 'volume') {
      const rawVolume = requestArg.data?.volume_level ?? requestArg.data?.volume;
      const volume = typeof rawVolume === 'number' && rawVolume <= 1 ? rawVolume * 100 : rawVolume;
      if (typeof volume !== 'number') {
        return { success: false, error: 'DLNA DMR volume service requires data.volume_level or data.volume.' };
      }
      await this.client.setVolume(volume);
      return { success: true };
    }

    if (requestArg.service === 'volume_mute' || requestArg.service === 'set_mute' || requestArg.service === 'mute') {
      const muted = requestArg.data?.is_volume_muted ?? requestArg.data?.muted;
      if (typeof muted !== 'boolean') {
        return { success: false, error: 'DLNA DMR mute service requires data.is_volume_muted or data.muted.' };
      }
      await this.client.setMute(muted);
      return { success: true };
    }

    if (requestArg.service === 'select_source') {
      const source = requestArg.data?.source;
      if (typeof source !== 'string' || !source) {
        return { success: false, error: 'DLNA DMR select_source requires data.source.' };
      }
      await this.client.selectSource(source);
      return { success: true };
    }

    if (requestArg.service === 'set_uri' || requestArg.service === 'play_media') {
      const uri = requestArg.data?.media_content_id ?? requestArg.data?.uri;
      if (typeof uri !== 'string' || !uri) {
        return { success: false, error: 'DLNA DMR set_uri requires data.media_content_id or data.uri.' };
      }
      const title = typeof requestArg.data?.title === 'string' ? requestArg.data.title : undefined;
      const metadata = typeof requestArg.data?.metadata === 'string' ? requestArg.data.metadata : undefined;
      const autoplay = typeof requestArg.data?.autoplay === 'boolean' ? requestArg.data.autoplay : requestArg.service === 'play_media';
      await this.client.setUri(uri, metadata, title, autoplay);
      return { success: true };
    }

    return { success: false, error: `Unsupported DLNA DMR media_player service: ${requestArg.service}` };
  }

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