package com.jld.vod.view.fragment


import android.content.Context
import android.content.Intent
import android.graphics.PixelFormat
import android.os.Build
import android.provider.Settings
import android.view.Gravity
import android.view.View
import android.view.WindowManager
import android.widget.Button
import android.widget.Toast
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.lifecycle.lifecycleScope
import androidx.paging.LoadState
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.jld.kotilntest.room.adapter.GameAdapter
import com.jld.vod.R
import com.jld.vod.base.BaseFragment
import com.jld.vod.model.bean.BaseBean
import com.jld.vod.model.bean.GameBean
import com.jld.vod.model.bean.ModelAllBean
import com.jld.vod.service.MyAccessibilityService
import com.jld.vod.utils.AppUtil
import com.jld.vod.utils.LogUtils
import com.jld.vod.utils.SharedPrefUtils
import com.jld.vod.utils.ShellUtils
import com.jld.vod.view.widget.CustomButton
import com.jld.vod.viewmodel.GameViewModel
import com.jld.vod.viewmodel.MainViewModel
import com.xuexiang.xpage.annotation.Page
import com.xuexiang.xpage.enums.CoreAnim
import com.xuexiang.xui.widget.actionbar.TitleBar
import com.xuexiang.xui.widget.statelayout.StatefulLayout
import kotlinx.coroutines.flow.collectLatest
import org.greenrobot.eventbus.EventBus

@Page(anim = CoreAnim.none)
class GameFragment : BaseFragment() {

    private lateinit var mRecyclerView: RecyclerView
    private lateinit var gameViewModel: GameViewModel
    private lateinit var floatView: Button
    private lateinit var  windowManager: WindowManager
    private var flag:Boolean = false

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

    override fun initViews() {

        mRecyclerView = findViewById(R.id.rv_game)
        floatView = CustomButton(activity!!.applicationContext)
        windowManager = activity!!.getSystemService(Context.WINDOW_SERVICE) as WindowManager

        //初始化viewmodel
        gameViewModel = ViewModelProviders.of(this)
            .get(GameViewModel::class.java)

        //初始化recyclerview
        val gridlayoutManager = GridLayoutManager(activity, 4)
        mRecyclerView!!.layoutManager = gridlayoutManager

        val adapter = GameAdapter()
        mRecyclerView!!.adapter = adapter

        val lid = SharedPrefUtils.getString(activity,"language_lid")
        val mid = SharedPrefUtils.getString(activity,"RES_GAME")

        if (lid != "" && mid !="")
        {
            lifecycleScope.launchWhenCreated {
                gameViewModel.getGameAllList(mid.toLong(),lid.toLong(),AppUtil.getDeviceSN()).collectLatest { pagingData ->
                    adapter.submitData(pagingData)
                }
            }
        }
        adapter.addLoadStateListener {
            when (it.refresh) {
                is LoadState.Error -> {
                    finishLoading()
                }
                is LoadState.Loading -> {
                    showLoading()
                }
                is LoadState.NotLoading -> {
                    finishLoading()
                }
            }
        }
//        val nameObserver = Observer<BaseBean<List<GameBean>>>{
//            if (it.data != null)
//            {
//                when (it?.code) {
//                    BaseBean.SUCCESS -> {
//                        finishLoading()
//                    }
//                    BaseBean.ERROR -> {
//                        finishLoading()
//                        Toast.makeText(activity, it.message, Toast.LENGTH_SHORT).show()
//                    }
//                    BaseBean.LOADING -> showLoading()
//                }
//            }else {
//                showNullGame()
//            }
//        }
//        gameViewModel.findGameAllliveData.observe(this,nameObserver)
       // gameViewModel.gameList.observe(this, Observer(adapter::submitList))

        adapter!!.setOnGameClickListener(object : GameAdapter.IGameItemClickListener{
            override fun onItemClickListener(install: String) {
                if (install != null)
                {
                    val isOpen = AppUtil.openAPK(activity,install)
                    if (isOpen)
                    {
                        buttonClick()
                    }
                }else{
                    Toast.makeText(activity,"This app is not installed",Toast.LENGTH_LONG).show()
                }
            }
        })
    }

    private fun showNullGame() {
        LogUtils.logD("showNullGame")

    }

    override fun initTitle(): TitleBar? {
        return null
    }

    /**
     * 打开返回键
     */
    fun buttonClick() {
        if (Build.VERSION.SDK_INT >= 23) {
            if (Settings.canDrawOverlays(activity)) {
                showFloatView()
            } else {
                val intent =
                    Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION)
                startActivity(intent)
            }
        } else {
            showFloatView()
        }
    }
    fun showFloatView() {
        flag = true
        val params: WindowManager.LayoutParams = WindowManager.LayoutParams()
        params.type = WindowManager.LayoutParams.TYPE_PHONE
        params.format = PixelFormat.RGBA_8888
        params.gravity = Gravity.RIGHT or Gravity.BOTTOM
        params.flags =
            WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
        params.width = 50
        params.height = 50
        params.x = 50
        params.y = 120
        windowManager.addView(floatView, params)

        //返回事件
        floatView.setOnClickListener {
            EventBus.getDefault().post(MyAccessibilityService.BACK)
//            Thread(Runnable {
//                ShellUtils.exec_shell("input keyevent 4")
//            }).start()
        }
    }

    override fun onResume() {
        super.onResume()
        if (flag)
        {
            flag = false
            disFloatView()
        }
    }

    fun disFloatView()
    {
        windowManager.removeView(floatView)
    }

    override fun onDestroy() {
        super.onDestroy()
//        mainViewModel.ByrtNamesLiveData.removeObserver( observer2)
    }
}