package com.mayi.fastdevelop.view;

import android.content.Context;
import android.net.Uri;
import android.util.AttributeSet;

import com.google.android.exoplayer2.ExoPlayerFactory;
import com.google.android.exoplayer2.PlaybackPreparer;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.database.DatabaseProvider;
import com.google.android.exoplayer2.database.ExoDatabaseProvider;
import com.google.android.exoplayer2.source.LoopingMediaSource;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.ProgressiveMediaSource;
import com.google.android.exoplayer2.ui.PlayerView;
import com.google.android.exoplayer2.upstream.DataSink;
import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.google.android.exoplayer2.upstream.DefaultHttpDataSourceFactory;
import com.google.android.exoplayer2.upstream.FileDataSourceFactory;
import com.google.android.exoplayer2.upstream.TransferListener;
import com.google.android.exoplayer2.upstream.cache.Cache;
import com.google.android.exoplayer2.upstream.cache.CacheDataSinkFactory;
import com.google.android.exoplayer2.upstream.cache.CacheDataSource;
import com.google.android.exoplayer2.upstream.cache.CacheDataSourceFactory;
import com.google.android.exoplayer2.upstream.cache.NoOpCacheEvictor;
import com.google.android.exoplayer2.upstream.cache.SimpleCache;
import com.google.android.exoplayer2.util.Util;

import java.io.File;

public class AppPlayerView extends PlayerView implements PlaybackPreparer {

    private static final String DOWNLOAD_CONTENT_DIRECTORY = "downloads";
    private SimpleExoPlayer player;
    private DatabaseProvider databaseProvider;
    private File downloadDirectory;
    private Cache downloadCache;

    public AppPlayerView(Context context) {
        super(context);
    }

    public AppPlayerView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public AppPlayerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    public void setUrl(String url, boolean isLooping) {
        if (player == null) {
            player = ExoPlayerFactory.newSimpleInstance(getContext());
            setPlayer(player);
            player.setPlayWhenReady(true);
            setPlaybackPreparer(this);
        }
        // 测量播放带宽，如果不需要可以传null
        TransferListener listener = new DefaultBandwidthMeter();
        DefaultDataSourceFactory upstreamFactory = new DefaultDataSourceFactory(getContext(), listener,
                new DefaultHttpDataSourceFactory(getContext().getPackageName(), listener));
        DataSink.Factory cacheWriteDataSinkFactory = new CacheDataSinkFactory(getDownloadCache(), Long.MAX_VALUE);
        CacheDataSourceFactory dataSourceFactory = new CacheDataSourceFactory(getDownloadCache(), upstreamFactory, new FileDataSourceFactory(), cacheWriteDataSinkFactory, CacheDataSource.FLAG_BLOCK_ON_CACHE | CacheDataSource.FLAG_IGNORE_CACHE_ON_ERROR, null);
        Uri uri = Uri.parse(url);
        MediaSource mediaSource = new ProgressiveMediaSource.Factory(dataSourceFactory).createMediaSource(uri);

        if (isLooping) {
            //循环播放
            LoopingMediaSource loopingMediaSource = new LoopingMediaSource(mediaSource);
            //使用资源准备播放器
            player.prepare(loopingMediaSource);
        } else {
            //使用资源准备播放器
            player.prepare(mediaSource);
        }
    }

    protected synchronized Cache getDownloadCache() {
        if (downloadCache == null) {
            File downloadContentDirectory = new File(getDownloadDirectory(), DOWNLOAD_CONTENT_DIRECTORY);
            downloadCache = new SimpleCache(downloadContentDirectory, new NoOpCacheEvictor(), getDatabaseProvider());
        }
        return downloadCache;
    }

    //释放播放器资源
    public void releasePlayer() {
        if (downloadCache != null) {
            downloadCache.release();
        }
        if (Util.SDK_INT <= 23) {
            onPause();
            releasePlayer();
        }
        if (player != null) {
            player.release();
        }
    }

    private File getDownloadDirectory() {
        if (downloadDirectory == null) {
            downloadDirectory = getContext().getExternalFilesDir(null);
            if (downloadDirectory == null) {
                downloadDirectory = getContext().getFilesDir();
            }
        }
        return downloadDirectory;
    }

    private DatabaseProvider getDatabaseProvider() {
        if (databaseProvider == null) {
            databaseProvider = new ExoDatabaseProvider(getContext());
        }
        return databaseProvider;
    }

    @Override
    public void preparePlayback() {
        player.retry();
    }
}
