package com.tencent.liteav.demo.player

import android.content.Intent
import android.view.View
import com.tencent.liteav.demo.superplayer.SuperPlayerView.OnSuperPlayerViewCallback
import com.tencent.liteav.demo.player.ui.PlayerListAdapter
import com.tencent.liteav.demo.player.ViewInsets.ViewportMetrics
import android.os.Bundle
import android.util.Log
import android.view.WindowManager
import androidx.activity.viewModels
import com.tencent.liteav.demo.superplayer.SuperPlayerDef
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewmodel.viewModelFactory
import androidx.recyclerview.widget.LinearLayoutManager
import com.tencent.liteav.demo.player.ui.PlayerListDecoration
import com.tencent.liteav.demo.superplayer.SuperPlayerGlobalConfig
import com.tencent.rtmp.TXLiveConstants
import com.tencent.liteav.demo.superplayer.SuperPlayerModel
import com.tencent.liteav.demo.player.util.PlayerModelProvider
import com.tencent.liteav.demo.player.databinding.ActivityPlayerBinding
import com.tencent.liteav.demo.player.viewmodel.PlayerViewModel
import com.tencent.liteav.demo.player.viewmodel.PlayerViewModelFactory
import com.tencent.liteav.demo.superplayer.database.PlayerDatabaseProvider
import com.tencent.liteav.demo.superplayer.database.entity.History

/**
 * Created by liyuejiao on 2018/7/3.
 * 超级播放器主Activity
 */
class PlayerActivity : AppCompatActivity(),
    View.OnClickListener,
    OnSuperPlayerViewCallback,
    PlayerListAdapter.OnItemClickListener {

    private var _viewBinding: ActivityPlayerBinding? = null
    private val viewBinding get() = _viewBinding!!

    private val activityLayout get() = viewBinding.superplayerActivity
    private val mLayoutTopBar get() = viewBinding.superplayerTcActionBar
    private val mLayoutList get() = viewBinding.superplayerRbList
    private val mLayoutPlayer get() = viewBinding.superplayerBlPlayer
    private val mImageBack get() = viewBinding.superplayerTcBack
    private val mTextTitle get() = viewBinding.superplayerTcUrl
    private val mImageLock get() = viewBinding.superplayerTcLock
    private val mImageMenu get() = viewBinding.superplayerTcMenu
    private val mSuperPlayerView get() = viewBinding.superVodPlayerView
    private val mVodPlayerListView get() = viewBinding.superplayerRecyclerView
    private lateinit var mVodPlayerListAdapter: PlayerListAdapter

    private var mIsManualPause = false

    private var viewInsets = ViewportMetrics()
    private val currentIndex = -1

    private val viewModel by viewModels<PlayerViewModel> {
        PlayerViewModelFactory(((application) as PlayerDatabaseProvider).getPlayerRepository())
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        _viewBinding = ActivityPlayerBinding.inflate(layoutInflater)
        setContentView(viewBinding.root)
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        initView()
        initData()
        updateList()

    }

    override fun onBackPressed() {
        if (isFullScreen) {
            mSuperPlayerView.switchPlayMode(SuperPlayerDef.PlayerMode.WINDOW)
        } else {
            super.onBackPressed()
        }
    }

    /**
     * 以16：9 比例显示播放器view，优先保证宽度完全填充
     */
    private fun adjustSuperPlayerViewAndMaskHeight() {
        val screenWidth = windowManager.defaultDisplay.width
        val layoutParams = mSuperPlayerView.layoutParams
        layoutParams.width = screenWidth
        layoutParams.height = (screenWidth * sPlayerViewDisplayRatio).toInt()
        mSuperPlayerView.layoutParams = layoutParams
        window.decorView.setOnApplyWindowInsetsListener { v, insets ->
            viewInsets = ViewInsets.applyWindowInsets(this@PlayerActivity, insets)
            setPadding()
            insets
        }
    }

    private fun initView() {
        mImageBack.setOnClickListener(this)
        mTextTitle.setOnClickListener(this)
        mImageLock.setOnClickListener(this)
        mImageMenu.setOnClickListener(this)
        mSuperPlayerView.setPlayerViewCallback(this)
        mVodPlayerListView.layoutManager = LinearLayoutManager(this)
        mVodPlayerListAdapter = PlayerListAdapter(this)
        mVodPlayerListAdapter.setOnItemClickListener(this)
        mVodPlayerListView.adapter = mVodPlayerListAdapter
        mVodPlayerListView.addItemDecoration(PlayerListDecoration())
        viewBinding.superplayerTcVerify.setOnClickListener(this)
        adjustSuperPlayerViewAndMaskHeight()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        when (requestCode) {
            0 -> {
                if (checkResultCode(resultCode)) {
                }
            }
            else -> {

            }
        }
    }

    fun checkResultCode(resultCode: Int): Boolean {
        return resultCode == RESULT_OK
    }

    private fun initData() {
        initSuperVodGlobalSetting()
    }

    /**
     * 初始化超级播放器全局配置
     */
    private fun initSuperVodGlobalSetting() {
        val prefs = SuperPlayerGlobalConfig.getInstance()
        prefs.maxCacheItem = 5
        prefs.enableHWAcceleration = true
        prefs.renderMode = TXLiveConstants.RENDER_MODE_ADJUST_RESOLUTION
    }

    override fun onResume() {
        super.onResume()
        if (mSuperPlayerView.playerState == SuperPlayerDef.PlayerState.PLAYING
            || mSuperPlayerView.playerState == SuperPlayerDef.PlayerState.PAUSE
        ) {
            Log.i(TAG, "onResume state :" + mSuperPlayerView.playerState)
            if (!mIsManualPause) {
                mSuperPlayerView.onResume()
            }
        }
        mSuperPlayerView.setNeedToPause(false)
    }

    override fun onPause() {
        super.onPause()
        Log.i(TAG, "onPause state :" + mSuperPlayerView.playerState)
        mIsManualPause = mSuperPlayerView.playerState == SuperPlayerDef.PlayerState.PAUSE
        mSuperPlayerView.onPause()
        mSuperPlayerView.setNeedToPause(true)
    }

    override fun onDestroy() {
        super.onDestroy()
        mSuperPlayerView.release()
        mSuperPlayerView.resetPlayer()
        _viewBinding = null
    }

    override fun onItemClick(videoModel: SuperPlayerModel, index: Int) {
        playVideoModel(index)
    }

    private fun playVideoModel(index: Int) {
        mSuperPlayerView.playWithModelList(PlayerModelProvider.getList(), true, index)
    }

    override fun onClick(v: View) {
        val id = v.id
        if (id == R.id.superplayer_tc_back) {
            finish()
        } else if (id == R.id.superplayer_tc_lock) {
            mSuperPlayerView.switchPlayMode(SuperPlayerDef.PlayerMode.FULLSCREEN)
        } else if (id == R.id.superplayer_tc_menu) {
            PlayerMenu.start(this@PlayerActivity, "")
        } else if (id == viewBinding.superplayerTcVerify.id) {
            PlayerVerify.start(this@PlayerActivity)
        }
    }

    private fun updateList() {
        mVodPlayerListAdapter.clear()
        for (videoModel in PlayerModelProvider.getList()) {
            mVodPlayerListAdapter.addSuperPlayerModel(videoModel)
        }
        mSuperPlayerView.playWithModelList(PlayerModelProvider.getList(), false, 0)
    }

    private var isFullScreen = false
    override fun onStartFullScreenPlay() {
        // 隐藏其他元素实现全屏
        mLayoutPlayer.onFullScreenMode()
        mLayoutTopBar.visibility = View.GONE
        mLayoutList.visibility = View.GONE
        isFullScreen = true
        setPadding()
    }

    override fun onStopFullScreenPlay() {
        // 恢复原有元素
        mLayoutPlayer.onWindowMode()
        mLayoutTopBar.visibility = View.VISIBLE
        mLayoutList.visibility = View.VISIBLE
        isFullScreen = false
        setPadding()
    }

    private fun setPadding() {
        if (!isFullScreen) {
            activityLayout.setPadding(
                viewInsets.viewPaddingLeft,
                viewInsets.viewPaddingTop,
                viewInsets.viewPaddingRight,
                viewInsets.viewPaddingBottom
            )
        } else {
            activityLayout.setPadding(0, 0, 0, 0)
        }
    }

    override fun onPlaying() {}
    override fun onPlayIndex(index: Int, model: SuperPlayerModel) {
        viewModel.saveHistory(History(start = 0, end = 10, courseId = model.url))
        mVodPlayerListAdapter.setIndex(index)
        (mVodPlayerListView.layoutManager as LinearLayoutManager?)!!.scrollToPositionWithOffset(
            index * 200,
            0
        )
    }

    override fun onPlayEnd() {}
    override fun onError(code: Int) {}

    companion object {
        private const val TAG = "SuperPlayerActivity"
        private const val sPlayerViewDisplayRatio =
            720.toFloat() / 1280 //当前界面播放器view展示的宽高比，用主流的16：9
    }
}