// DRM Configuration for DRMtoday integration
import { Logger } from "./utils/logger.js";

export const DRM_TYPES = {
  WIDEVINE: "com.widevine.alpha",
  FAIRPLAY: "com.apple.fps.1_0",
  PLAYREADY: "com.microsoft.playready",
};

export function setupDRM(player, source, drmConfig = {}, logger = null) {
  // Use provided logger or create a default one
  const log = logger || new Logger("DRM");
  
  if (!player || !drmConfig) {
    log.warn("DRM setup requires player and drmConfig");
    return;
  }

  const DRMConfig = {};
  // const drmSupport = detectDRMSupport(); TODO: add detectDRMSupport

  // Default DRMtoday configuration if not provided
  if (drmConfig.widevine) {
    DRMConfig.widevine = {
      url:
        drmConfig.widevine.url ??
        "https://lic.staging.drmtoday.com/license-proxy-widevine/cenc/?specConform=true",
      licenseHeaders: drmConfig.widevine.licenseHeaders ?? {},
    };
  }

  if (drmConfig.fairplay) {
    DRMConfig.fairplay = {
      certificateUrl: drmConfig.fairplay.certificateUrl ?? "https://lic.staging.drmtoday.com/license-server-fairplay/cert/orca",
      url: drmConfig.fairplay.url ?? "https://lic.staging.drmtoday.com/license-server-fairplay/",
      licenseHeaders: drmConfig.fairplay.licenseHeaders ?? {}
    };
  }

  if (drmConfig.playready) {
    DRMConfig.playready = {
      url:
        drmConfig.playready.url ??
        "https://lic.staging.drmtoday.com/license-proxy-headerauth/drmtoday/RightsManager.asmx",
      licenseHeaders: drmConfig.playready.licenseHeaders ?? {},
    };
  }

  // Setup EME (Encrypted Media Extensions)
  if (player.eme) {
    const keySystems = buildKeySystemsConfig(DRMConfig);

    player.ready(() => {
      player.eme();
      if (drmConfig.fairplay) {
        player.eme.initLegacyFairplay();
      }

      // Configure key systems
      if (Object.keys(keySystems).length > 0) {
        try {
          player.src({
            src: source.url,
            keySystems,
          });
        } catch (error) {
          log.error("Error setting DRM source:", error);
        }
      }
    });

   // Add DRM event listeners
    addDRMEventListeners(player, log);
  } else {
    log.error("videojs-contrib-eme plugin is required for DRM support");
  }
}

function buildKeySystemsConfig(drmConfig) {
  const keySystems = {};

  // Widevine configuration
  if (drmConfig.widevine && drmConfig.widevine.url && drmConfig.widevine.licenseHeaders) {
    keySystems[DRM_TYPES.WIDEVINE] = {
      // initDataTypes: ['cenc', 'webm'],
      url: drmConfig.widevine.url,
      licenseHeaders: drmConfig.widevine.licenseHeaders ?? {},
      // audioContentType: 'audio/mp4; codecs="mp4a.40.2"',
      // videoContentType: 'video/mp4; codecs="avc1.640028"',
      // audioRobustness: "SW_SECURE_CRYPTO",
      // videoRobustness: "SW_SECURE_CRYPTO",
    };
  }

  // FairPlay configuration
  if (
    drmConfig.fairplay &&
    drmConfig.fairplay.certificateUrl &&
    drmConfig.fairplay.url &&
    drmConfig.fairplay.licenseHeaders
  ) {
    keySystems[DRM_TYPES.FAIRPLAY] = {
      getContentId: (emeOptions, initData) => initData,
      getCertificate: function (emeOptions, callback) {
        videojs.xhr(
          {
            url: drmConfig.fairplay.certificateUrl,
            method: "GET",
            responseType: "arraybuffer",
          },
          (err, response, responseBody) => {
            callback(null, new Uint8Array(responseBody));
          }
        );
      },
      getLicense: function (emeOptions, contentId, keyMessage, callback) {
        videojs.xhr(
          {
            url: drmConfig.fairplay.url,
            method: "POST",
            responseType: "text",
            body: keyMessage,
            headers: {
              ...(drmConfig.fairplay.licenseHeaders ?? {}),
            },
          },
          (err, response, responseBody) => {
            let rawLicenseString = atob(responseBody);
            let data = new Uint8Array(rawLicenseString.length);
            for (let i = 0; i < rawLicenseString.length; ++i) {
              data[i] = rawLicenseString.charCodeAt(i);
            }
            let key = data.buffer;
            callback(null, key);
          }
        );
      },
    };
  }

  // PlayReady configuration
  if (drmConfig.playready && drmConfig.playready.url) {
    keySystems[DRM_TYPES.PLAYREADY] = {
      url: drmConfig.playready.url,
      licenseHeaders: drmConfig.playready.licenseHeaders || {},
    };
  }

  return keySystems;
}

function addDRMEventListeners(player, logger = null) {
  const log = logger || new Logger("DRM");
  
  player.on("eme-error", (event) => {
    log.error("EME Error:", event);
    handleDRMError(event, player, null, log);
  });

  player.on("eme-keystatuschange", (event) => {
    log.info("Key Status Change:", event);
  });

  player.on("eme-keysessioncreated", (event) => {
    log.info("Key Session Created:", event);
  });
}

function handleDRMError(error, player, videoId, logger = null) {
  const log = logger || new Logger("DRM");
  log.error("DRM Error Details:", error);

  // Emit custom DRM error event
  if (videoId) {
    const customEvent = new CustomEvent(
      `${videoId}-videojs-drm-player:drm-error`,
      {
        detail: {
          error: error,
          player: player,
        },
      }
    );
    document.dispatchEvent(customEvent);
  }

  // Log error but don't stop playback
  // Don't call player.error() as it would stop playback
}

// TODO: VideoJS - DRM detection problem - Helper function to detect DRM support 
// export function detectDRMSupport() {
//   const support = {
//     widevine: false,
//     fairplay: false,
//     playready: false,
//   };

//   if (window.navigator && window.navigator.requestMediaKeySystemAccess) {
//     // Check Widevine support
//     navigator
//       .requestMediaKeySystemAccess(DRM_TYPES.WIDEVINE, [
//         {
//           initDataTypes: ["cenc"],
//           videoCapabilities: [
//             {
//               contentType: 'video/mp4; codecs="avc1.42E01E"',
//             },
//           ],
//         },
//       ])
//       .then(() => {
//         support.widevine = true;
//       })
//       .catch(() => {
//         support.widevine = false;
//       });

//     // Check FairPlay support (Safari only)
//     if (window.WebKitMediaKeys) {
//       support.fairplay = true;
//     }

//     // Check PlayReady support
//     navigator
//       .requestMediaKeySystemAccess(DRM_TYPES.PLAYREADY, [
//         {
//           initDataTypes: ["cenc"],
//           videoCapabilities: [
//             {
//               contentType: 'video/mp4; codecs="avc1.42E01E"',
//             },
//           ],
//         },
//       ])
//       .then(() => {
//         support.playready = true;
//       })
//       .catch(() => {
//         support.playready = false;
//       });
//   }

//   return support;
// }
