package com.gh.ad

import android.app.Activity
import android.content.Context
import android.util.AttributeSet
import android.view.WindowManager
import com.gh.gamecenter.R
import com.gh.gamecenter.video.detail.CustomManager
import com.shuyu.gsyvideoplayer.utils.GSYVideoType
import com.shuyu.gsyvideoplayer.utils.GSYVideoType.SCREEN_TYPE_FULL
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer
import com.shuyu.gsyvideoplayer.video.base.GSYVideoViewBridge

class SplashAdVideoView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null
) :
    StandardGSYVideoPlayer(context, attrs) {

    fun startPlay(url: String) {
        GSYVideoType.setShowType(SCREEN_TYPE_FULL)
        GSYVideoType.setRenderType(GSYVideoType.SUFRACE)
        CustomManager.getCustomManager(getKey()).isNeedMute = true

        setUp(url, true, "")

        setNeedAutoAdaptation(false)
        startPlayLogic()
    }

    override fun getGSYVideoManager(): GSYVideoViewBridge {
        CustomManager.getCustomManager(getKey()).initContext(context.applicationContext)
        return CustomManager.getCustomManager(getKey())
    }

    private fun getKey() = "splash_ad"

    /**
     * 覆盖父类方法，防止在是视频 Preparing 阶段封面图被隐藏，导致白屏
     */
    override fun changeUiToPreparingShow() = Unit

    override fun getLayoutId(): Int {
        return R.layout.layout_splash_ad_video
    }

    override fun touchSurfaceMoveFullLogic(absDeltaX: Float, absDeltaY: Float) {
        // no nothing
    }

    override fun onPrepared() {
        super.onPrepared()

        visibility = VISIBLE
    }

    override fun onAutoCompletion() {
        setStateAndUi(CURRENT_STATE_AUTO_COMPLETE);

        mSaveChangeViewTIme = 0
        mCurrentPosition = 0

        if (!mIfCurrentIsFullscreen) {
            getGSYVideoManager().setLastListener(null)
        }
        mAudioManager.abandonAudioFocus(onAudioFocusChangeListener);
        if (mContext is Activity) {
            try {
                (mContext as Activity).getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        releaseNetWorkState()

        if (mVideoAllCallBack != null && isCurrentMediaListener()) {
            mVideoAllCallBack.onAutoComplete(mOriginUrl, mTitle, this)
        }
        mHadPlay = false
    }

    fun clearAll() {
        GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_DEFAULT)
        GSYVideoType.setRenderType(GSYVideoType.TEXTURE)
        release()
        CustomManager.removeManager(getKey())
    }
}