import { formatQualityLabel, sortQualityTracks } from '../helpers/renditionHelper';
import { Logger } from '../utils/logger.js';

const AUTO_QUALITY_LEVEL = {
  id: -1,
  label: 'Auto',
  height: null,
  width: null,
  bandwidth: null
};

function _getQuality(tech, shakaPlayer) { 
  const logger = new Logger("Shaka-Quality");
  const tracks = [AUTO_QUALITY_LEVEL];

  const levels = shakaPlayer.getVariantTracks();
  logger.info('Raw variant tracks:', levels);

  levels.forEach(function(level, index) {
    tracks.push({
      id: level.id ?? index,
      label: formatQualityLabel(level) || `Quality ${index + 1}`,
      height: level.height,
      width: level.width,
      bandwidth: level.bandwidth,
    });
  });

  // Sort tracks by height (highest first), but keep Auto first
  return tracks.sort(sortQualityTracks);
}

export default function setupQualityTracks(tech, shakaPlayer) {  
  const logger = new Logger("Shaka-Quality");
  const qualityData = _getQuality(tech, shakaPlayer);
  logger.info('Quality tracks found:', qualityData);

  tech.trigger('loadedqualitydata', {
    qualityData: {
      video: qualityData
    },
    qualitySwitchCallback: function(id, type) {
      logger.info('Quality switch callback called with id:', id, type);
      if (type !== 'video') return;

      // Update the adaptation.
      shakaPlayer.configure({
        abr: {
          enabled: id === AUTO_QUALITY_LEVEL.id
        }
      });

      // Is auto?
      if (id === AUTO_QUALITY_LEVEL.id) return;

      const tracks = shakaPlayer.getVariantTracks().filter(t => Number(t.id) === Number(id));
      logger.info('Selected variant track:', tracks[0]);

      if (tracks.length > 0) {
        shakaPlayer.selectVariantTrack(tracks[0], /* clearBuffer */ true);
        
        // Trigger quality change event for Video.js
        tech.player().trigger('qualitychange', {
          quality: tracks[0]
        });
      }

      // fire `variantchanged` event - only supports debug mode right now
      // todo - need to figure out how to do this in non debug mode
      // if (shaka.util.FakeEvent) {
      //   const event = new shaka.util.FakeEvent('variantchanged');
      //   shakaPlayer.dispatchEvent(event);
      // }
    }
  });
}