package com.gh.gamecenter.video.detail;

import android.content.Context;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.os.Handler;

import com.gh.common.video.CustomExo2PlayerManager;
import com.gh.common.video.CustomExoPlayerCacheManager;
import com.google.android.exoplayer2.DefaultLoadControl;
import com.shuyu.gsyvideoplayer.GSYVideoBaseManager;
import com.shuyu.gsyvideoplayer.cache.ICacheManager;
import com.shuyu.gsyvideoplayer.model.GSYModel;
import com.shuyu.gsyvideoplayer.player.BasePlayerManager;
import com.shuyu.gsyvideoplayer.player.IPlayerManager;
import com.shuyu.gsyvideoplayer.utils.CommonUtil;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import tv.danmaku.ijk.media.exo2.IjkExo2MediaPlayer;
import tv.danmaku.ijk.media.player.IMediaPlayer;

import static com.shuyu.gsyvideoplayer.utils.CommonUtil.hideNavKey;

/**
 * 多个播放的管理器
 * Created by guoshuyu on 2018/1/31.
 */

public class CustomManager extends GSYVideoBaseManager {

    private IPlayerManager mPlayerManager;

    private ICacheManager mPlayerCacheManager;

    public static final int SMALL_ID = com.shuyu.gsyvideoplayer.R.id.small_id;

    public static final int FULLSCREEN_ID = com.shuyu.gsyvideoplayer.R.id.full_id;

    public static String TAG = "GSYVideoManager";

    private static Map<String, CustomManager> sMap = new HashMap<>();

    private static final int DEFAULT_MIN_BUFFER_MS = 10 * 1000;

    private static final int DEFAULT_MAX_BUFFER_MS = 20 * 1000;

    private Runnable mPrepareRunnable;


    public CustomManager() {
        init();
    }

    @Override
    protected IPlayerManager getPlayManager() {
        if (mPlayerManager == null) {
            mPlayerManager = new CustomExo2PlayerManager();
        }

        return mPlayerManager;
    }

    @Override
    protected ICacheManager getCacheManager() {
        if (mPlayerCacheManager == null) {
            mPlayerCacheManager = new CustomExoPlayerCacheManager();
        }

        return mPlayerCacheManager;
    }

    /**
     * 页面销毁了记得调用是否所有的video
     */
    public static void releaseAllVideos(String key) {
        if (getCustomManager(key).listener() != null) {
            getCustomManager(key).listener().onCompletion();
        }
        getCustomManager(key).releaseMediaPlayer();
    }

    @Override
    public void releaseMediaPlayer() {
        // Handler队列优化，Message复用优化
        clearMessages(HANDLER_RELEASE);
        Message msg = Message.obtain();
        msg.what = HANDLER_RELEASE;
        sendMessage(msg);
        playTag = "";
        playPosition = -22;
    }

    private void clearMessages(int what) {
        ((Handler)mMediaHandler).removeMessages(what);
    }

    private void clearCallbacks(Runnable runnable) {
        ((Handler)mMediaHandler).removeCallbacks(runnable);
    }

    private void sendCallback(Runnable runnable) {
        ((Handler)mMediaHandler).post(runnable);
    }

    @Override
    public void prepare(final String url, final Map<String, String> mapHeadData, boolean loop, float speed, boolean cache, File cachePath, String overrideExtension) {
        if (TextUtils.isEmpty(url)) return;
        // Handler队列优化
        if (mPrepareRunnable != null) {
            clearCallbacks(mPrepareRunnable);
        }
        mPrepareRunnable = new PrepareRunnable(new GSYModel(url, mapHeadData, loop, speed, cache, cachePath, overrideExtension));
        sendCallback(mPrepareRunnable);
        if (needTimeOutOther) {
            startTimeOutBuffer();
        }
    }

    private void initVideo(Message msg) {
        try {
            currentVideoWidth = 0;
            currentVideoHeight = 0;

            if (playerManager != null) {
                playerManager.stop();
            }
            playerManager = getPlayManager();
            cacheManager = getCacheManager();
            if (cacheManager != null) {
                cacheManager.setCacheAvailableListener(this);
            }
            if (playerManager instanceof BasePlayerManager) {
                ((BasePlayerManager) playerManager)
                        .setPlayerInitSuccessListener(mPlayerInitSuccessListener);
            }
            playerManager.initVideoPlayer(context, msg, optionModelList, cacheManager);

            setNeedMute(needMute);
            IMediaPlayer mediaPlayer = playerManager.getMediaPlayer();
            mediaPlayer.setOnCompletionListener(this);
            mediaPlayer.setOnBufferingUpdateListener(this);
            mediaPlayer.setScreenOnWhilePlaying(true);
            mediaPlayer.setOnPreparedListener(this);
            mediaPlayer.setOnSeekCompleteListener(this);
            mediaPlayer.setOnErrorListener(this);
            mediaPlayer.setOnInfoListener(this);
            mediaPlayer.setOnVideoSizeChangedListener(this);
            mediaPlayer.prepareAsync();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void stop() {
        if (mPrepareRunnable != null) {
            clearCallbacks(mPrepareRunnable);
        }

        if (playerManager != null) {
            playerManager.stop();
        }
    }

    public static int getVideoManagerSize() {
        return sMap.size();
    }


    /**
     * 暂停播放
     */
    public static void onPause(String key) {
        if (getCustomManager(key).listener() != null) {
            getCustomManager(key).listener().onVideoPause();
        }
    }

    /**
     * 恢复播放
     */
    public static void onResume(String key) {
        if (getCustomManager(key).listener() != null) {
            getCustomManager(key).listener().onVideoResume(false);
        }
    }

    /**
     * 恢复暂停状态
     *
     * @param seek 是否产生seek动作,直播设置为false
     */
    public static void onResume(String key, boolean seek) {
        if (getCustomManager(key).listener() != null) {
            getCustomManager(key).listener().onVideoResume(seek);
        }
    }


    /**
     * 单例管理器
     */
    public static synchronized Map<String, CustomManager> instance() {
        return sMap;
    }

    /**
     * 单例管理器
     */
    public static synchronized CustomManager getCustomManager(String key) {
        if (TextUtils.isEmpty(key)) {
            throw new IllegalStateException("key not be empty");
        }
        CustomManager customManager = sMap.get(key);
        if (customManager == null) {
            customManager = new CustomManager();
            customManager.setPlayerInitSuccessListener((player, model) -> {
                if (player instanceof IjkExo2MediaPlayer) {
                    DefaultLoadControl defaultLoadControl = new DefaultLoadControl.Builder().
                            setBufferDurationsMs(DEFAULT_MIN_BUFFER_MS, DEFAULT_MAX_BUFFER_MS,
                                    DefaultLoadControl.DEFAULT_BUFFER_FOR_PLAYBACK_MS,
                                    DefaultLoadControl.DEFAULT_BUFFER_FOR_PLAYBACK_AFTER_REBUFFER_MS)
                            .createDefaultLoadControl();
                    ((IjkExo2MediaPlayer) player).setLoadControl(defaultLoadControl);
                }
            });
            sMap.put(key, customManager);
        }
        return customManager;
    }

    public static void onPauseAll() {
        if (sMap.size() > 0) {
            for (Map.Entry<String, CustomManager> header : sMap.entrySet()) {
                onPause(header.getKey());
            }
        }
    }

    public static void onResumeAll() {
        if (sMap.size() > 0) {
            for (Map.Entry<String, CustomManager> header : sMap.entrySet()) {
                onResume(header.getKey());
            }
        }
    }

    /**
     * 恢复暂停状态
     *
     * @param seek 是否产生seek动作
     */
    public static void onResumeAll(boolean seek) {
        if (sMap.size() > 0) {
            for (Map.Entry<String, CustomManager> header : sMap.entrySet()) {
                onResume(header.getKey(), seek);
            }
        }
    }

    public static void clearAllVideo() {
        if (sMap.size() > 0) {
            for (Map.Entry<String, CustomManager> header : sMap.entrySet()) {
                CustomManager.releaseAllVideos(header.getKey());
            }
        }
        sMap.clear();
    }

    public static void removeManager(String key) {
        sMap.remove(key);
    }

    /**
     * 退出全屏，主要用于返回键
     *
     * @return 返回是否全屏
     */
    @SuppressWarnings("ResourceType")
    public static boolean backFromWindowFull(Context context, String key) {
        boolean backFrom = false;
        ViewGroup vp = (CommonUtil.scanForActivity(context)).findViewById(Window.ID_ANDROID_CONTENT);
        View oldF = vp.findViewById(FULLSCREEN_ID);
        if (oldF != null) {
            backFrom = true;
            hideNavKey(context);
            if (getCustomManager(key).lastListener() != null) {
                getCustomManager(key).lastListener().onBackFullscreen();
            }
        }
        return backFrom;
    }

    private class PrepareRunnable implements Runnable {
        private final GSYModel model;

        public PrepareRunnable(GSYModel model) {
            this.model = model;
        }

        @Override
        public void run() {
            Message msg = Message.obtain();
            msg.obj = model;
            initVideo(msg);
        }
    }

}
