package com.hi.music.player.media3;

import android.net.Uri;

import androidx.media3.common.MediaItem;
import androidx.media3.common.util.UnstableApi;
import androidx.media3.datasource.DataSource;
import androidx.media3.datasource.DataSpec;
import androidx.media3.datasource.DefaultDataSource;
import androidx.media3.datasource.DefaultDataSourceFactory;
import androidx.media3.datasource.DefaultHttpDataSource;
import androidx.media3.datasource.ResolvingDataSource;
import androidx.media3.datasource.cache.CacheDataSource;
import androidx.media3.datasource.cache.SimpleCache;
import androidx.media3.exoplayer.ExoPlayer;
import androidx.media3.exoplayer.drm.DrmSessionManagerProvider;
import androidx.media3.exoplayer.source.DefaultMediaSourceFactory;
import androidx.media3.exoplayer.source.MediaSource;
import androidx.media3.exoplayer.source.MediaSourceFactory;
import androidx.media3.exoplayer.source.ProgressiveMediaSource;
import androidx.media3.exoplayer.upstream.LoadErrorHandlingPolicy;

import com.hi.music.player.MusicApplication;
import com.hi.music.player.api.RequestListener;
import com.hi.music.player.helper.CommonUtils;
import com.hi.music.player.javabean.response.ResponsePlayUrl;
import com.hi.music.player.network.JsonHelper;
import com.hi.music.player.network.RetrofitManager;

import org.json.JSONObject;

import java.io.IOException;

import okhttp3.ResponseBody;


public class DynamicMediaSourceFactory implements MediaSource.Factory {
    //    private final CacheDataSource.Factory cacheDataSourceFactory;
//    private final ExoPlayer player;
    private DataSource.Factory mediaSourceFactory;
    private SimpleCache simpleCache;

    //    public DynamicMediaSourceFactory(DefaultMediaSourceFactory factory,CacheDataSource.Factory cacheDataSourceFactory, ExoPlayer exoPlayer) {
//        this.cacheDataSourceFactory = cacheDataSourceFactory;
//        this.player = exoPlayer;
//        this.mediaSourceFactory = factory;
//    }
    public DynamicMediaSourceFactory(DataSource.Factory factory, SimpleCache cache) {

        this.mediaSourceFactory = factory;
        this.simpleCache = cache;
    }


    @UnstableApi
    @Override
    public MediaSource.Factory setDrmSessionManagerProvider(DrmSessionManagerProvider drmSessionManagerProvider) {
        return null;
    }

    @UnstableApi
    @Override
    public MediaSource.Factory setLoadErrorHandlingPolicy(LoadErrorHandlingPolicy loadErrorHandlingPolicy) {
        return null;
    }

    @UnstableApi
    @Override
    public int[] getSupportedTypes() {
        return new int[0];
    }

    @UnstableApi
    @Override
    public MediaSource createMediaSource(MediaItem mediaItem) {


        CommonUtils.LogMsg("------createMediaSource----------=" + mediaItem.mediaId + "---------" + mediaItem.mediaMetadata.title);
//        MediaSource realMediaSource = new ProgressiveMediaSource.Factory(cacheDataSourceFactory)
//                .createMediaSource(MediaItem.fromUri(""));
//        RetrofitManager.getInstance().getPlayUrl(mediaItem.mediaId, new RequestListener<ResponseBody>() {
//
//            @Override
//            public void onFail(String errorMsg) {
//
//            }
//
//            @Override
//            public void onSuccess(ResponseBody data) {
//                JSONObject jsonObject = CommonUtils.toJsonObject(data);
//                if (jsonObject != null) {
//                    ResponsePlayUrl responsePlayUrl = JsonHelper.ResolvePlayUrlJson(jsonObject);
//                    if (responsePlayUrl == null) {
//                        // TODO: 2024/9/27
//                        return;
//                    }
//                    String uri = "";
//                    if (responsePlayUrl.getAudioUrlMedium() != null) {
//                        uri = responsePlayUrl.getAudioUrlMedium();
//                    } else {
//                        uri = responsePlayUrl.getAudioUrlLow();
//                    }
//                    CommonUtils.LogMsg("------createMediaSource----------="+mediaItem.mediaId+"---------"+uri);
//                    ProgressiveMediaSource mediaSource = new ProgressiveMediaSource.Factory(cacheDataSourceFactory)
//                            .createMediaSource(MediaItem.fromUri(uri));
//                    player.setMediaSource(mediaSource);
//                    player.prepare();
//
//                }
//
//
//            }
//        });



//        DefaultHttpDataSource.Factory httpDataSourceFactory = new DefaultHttpDataSource.Factory().setAllowCrossProtocolRedirects(true);
// 这里的DefaultDataSource同时支持本地和HTTP请求的资源，自动实现检测 （The DefaultDataSource supports both local and Http sources. It automatically detects which one to use.）

       //实现缓存
        CacheDataSource.Factory cacheDataSourceFactory = new CacheDataSource.Factory()
                .setCache(simpleCache)
                .setUpstreamDataSourceFactory(mediaSourceFactory)
                .setFlags(CacheDataSource.FLAG_IGNORE_CACHE_ON_ERROR);

        MediaSource mediaSource = new ProgressiveMediaSource.Factory(cacheDataSourceFactory)
                .createMediaSource(mediaItem);

    return   mediaSource;



//        return new ProgressiveMediaSource.Factory(cacheDataSourceFactory)
//                .createMediaSource(MediaItem.fromUri(responsePlayUrl.getAudioUrlMedium()));
        // 可以在这里根据 mediaItem 的 ID 动态生成新的 URI
//        String updatedUri = "https://rr1---sn-tt1e7nlz.googlevideo.com/videoplayback?expire=1727628605&ei=3TD5ZuWFEe-yzN0P27WuqQ4&ip=146.19.167.8&id=o-ANGM0PjEvsfYH7TmYV_DFuD-65tipJeeLe2URDOk90sL&itag=140&source=youtube&requiressl=yes&xpc=EgVo2aDSNQ%3D%3D&mh=xj&mm=31%2C29&mn=sn-tt1e7nlz%2Csn-vgqsknsk&ms=au%2Crdu&mv=m&mvi=1&pl=24&pcm2=no&gcr=us&initcwndbps=7610000&vprv=1&svpuc=1&mime=audio%2Fmp4&rqh=1&gir=yes&clen=5440168&dur=335.973&lmt=1709326903801285&mt=1727606690&fvip=5&keepalive=yes&fexp=51299152&c=ANDROID_MUSIC&txp=2318224&sparams=expire%2Cei%2Cip%2Cid%2Citag%2Csource%2Crequiressl%2Cxpc%2Cpcm2%2Cgcr%2Cvprv%2Csvpuc%2Cmime%2Crqh%2Cgir%2Cclen%2Cdur%2Clmt&sig=AJfQdSswRQIhALmM_S8Cmagr60muB3wDOby0OdcjF-x6f7TcEenixH0KAiAnR0-hmA03MeVzSg2wi5ncJ4Ve5FFlpZnlSoRNGWgGhQ%3D%3D&lsparams=mh%2Cmm%2Cmn%2Cms%2Cmv%2Cmvi%2Cpl%2Cinitcwndbps&lsig=ABPmVW0wRQIhAPv5slfEnf8_E7o6yjEkussQ6JIFFaSY6QtP9HXncTTcAiAjlhMa71t76Wu1R1rcmsHoO6pyxjhGYouio4D0deJqEA%3D%3D";
//        Uri updateUri = null;
//
//        MediaItem.Builder builder = mediaItem.buildUpon();
//        if (mediaItem.localConfiguration != null) {
//            updateUri = mediaItem.localConfiguration.uri;
//            builder.setUri(updateUri);
//            CommonUtils.LogErrorMsg("----updateUri=成功  builder="+mediaItem.mediaId+"--updateUri="+updateUri);
//        }else {
//            CommonUtils.LogErrorMsg("----updateUri=null  builder="+mediaItem.mediaId);
//        }

//        return mediaSourceFactory.createMediaSource(builder.build());

    }

//    @UnstableApi
//    @Override
//    public DataSource createDataSource() {
//
//
//
//
////        RetrofitManager.getInstance().getPlayUrl(mediaItem.mediaId, new RequestListener<ResponseBody>() {
////
////            @Override
////            public void onFail(String errorMsg) {
////
////            }
////
////            @Override
////            public void onSuccess(ResponseBody data) {
////                JSONObject jsonObject = CommonUtils.toJsonObject(data);
////                if (jsonObject != null) {
////                    ResponsePlayUrl responsePlayUrl = JsonHelper.ResolvePlayUrlJson(jsonObject);
////                    if (responsePlayUrl == null) {
////                        // TODO: 2024/9/27
////                        return;
////                    }
////                    String uri = "";
////                    if (responsePlayUrl.getAudioUrlMedium() != null) {
////                        uri = responsePlayUrl.getAudioUrlMedium();
////                    } else {
////                        uri = responsePlayUrl.getAudioUrlLow();
////                    }
////                    CommonUtils.LogMsg("------createMediaSource----------="+mediaItem.mediaId+"---------"+uri);
////                    ProgressiveMediaSource mediaSource = new ProgressiveMediaSource.Factory(cacheDataSourceFactory)
////                            .createMediaSource(MediaItem.fromUri(uri));
////                    player.setMediaSource(mediaSource);
////                    player.prepare();
////
////                }
////
////
////            }
////        });
//        return null;
//    }
}
