import type { IConfigFlow, IConfigFlowContext, IConfigFlowStep, IDiscoveryCandidate } from '../../core/types.js';
import type { IDlnaDmrConfig } from './dlna_dmr.types.js';

export class DlnaDmrConfigFlow implements IConfigFlow<IDlnaDmrConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<IDlnaDmrConfig>> {
    void contextArg;
    if (candidateArg.source === 'ssdp' && typeof candidateArg.metadata?.location === 'string') {
      return {
        kind: 'done',
        title: candidateArg.name || 'DLNA Digital Media Renderer configured',
        config: {
          location: candidateArg.metadata.location,
          deviceId: candidateArg.id,
          udn: candidateArg.id,
          deviceType: typeof candidateArg.metadata.deviceType === 'string' ? candidateArg.metadata.deviceType : undefined,
          name: candidateArg.name,
          manufacturer: candidateArg.manufacturer,
          model: candidateArg.model,
          macAddress: candidateArg.macAddress,
        },
      };
    }

    return {
      kind: 'form',
      title: 'Manual DLNA DMR device connection',
      description: 'Enter the URL of the renderer device description XML file.',
      fields: [
        { name: 'url', label: 'Description URL', type: 'text', required: true },
      ],
      submit: async (valuesArg) => {
        const url = valuesArg.url;
        if (typeof url !== 'string' || !url) {
          return { kind: 'error', title: 'Invalid DLNA DMR configuration', error: 'A description URL is required.' };
        }
        return {
          kind: 'done',
          title: 'DLNA DMR configured',
          config: {
            location: url,
            url,
            deviceId: candidateArg.id,
            udn: candidateArg.id,
            name: candidateArg.name,
            manufacturer: candidateArg.manufacturer,
            model: candidateArg.model,
          },
        };
      },
    };
  }
}
