import { BaseDRM } from './BaseDRM';
import { KEY_SYSTEMS, DRMInitResult, DRMErrorCode } from '../types/DRMTypes';
import { DRMErrorHandler } from '../utils/DRMErrorHandler';

export class WidevineDRM extends BaseDRM {
  getKeySystem(): string { return KEY_SYSTEMS.WIDEVINE; }

  async initialize(): Promise<DRMInitResult> {
    try {
      const config: MediaKeySystemConfiguration[] = [{
        initDataTypes: ['cenc'],
        videoCapabilities: [{
          contentType: 'video/mp4; codecs="avc1.42E01E"',
          robustness: this.config.videoRobustness || 'SW_SECURE_CRYPTO',
        }],
        audioCapabilities: [{
          contentType: 'audio/mp4; codecs="mp4a.40.2"',
          robustness: this.config.audioRobustness || 'SW_SECURE_CRYPTO',
        }],
        persistentState: this.config.persistentState || 'optional',
        distinctiveIdentifier: this.config.distinctiveIdentifier || 'optional',
      }];

      await navigator.requestMediaKeySystemAccess(KEY_SYSTEMS.WIDEVINE, config);
      this.log('Widevine access granted');
      return { success: true, drmType: 'widevine', keySystem: KEY_SYSTEMS.WIDEVINE };
    } catch (error: any) {
      return {
        success: false,
        error: DRMErrorHandler.createError(DRMErrorCode.INITIALIZATION_FAILED, `Widevine init failed: ${error.message}`, error),
      };
    }
  }

  getHLSConfig(): Record<string, any> {
    return {
      emeEnabled: true,
      widevineLicenseUrl: this.config.licenseUrl,
      drmSystems: {
        'com.widevine.alpha': {
          licenseUrl: this.config.licenseUrl,
        },
      },
      licenseXhrSetup: this.config.headers
        ? (xhr: XMLHttpRequest) => {
            for (const [k, v] of Object.entries(this.config.headers!)) {
              xhr.setRequestHeader(k, v);
            }
          }
        : undefined,
    };
  }

  getDashProtectionData(): Record<string, any> {
    return {
      [KEY_SYSTEMS.WIDEVINE]: {
        serverURL: this.config.licenseUrl,
        httpRequestHeaders: this.config.headers || {},
        withCredentials: this.config.withCredentials || false,
      },
    };
  }

  async destroy(): Promise<void> {
    this.log('Widevine DRM destroyed');
  }
}
