package com.gh.gamecenter.personalhome

import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import androidx.recyclerview.widget.GridLayoutManager
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.base.TrackableDialog
import com.gh.gamecenter.core.utils.MtaHelper
import com.gh.gamecenter.core.utils.SPUtils
import com.gh.gamecenter.common.utils.debounceActionWithInterval
import com.gh.gamecenter.common.utils.dip2px
import com.gh.gamecenter.common.view.SpacingItemDecoration
import com.gh.gamecenter.R
import com.gh.gamecenter.databinding.DialogInstalledGameBinding
import com.gh.gamecenter.entity.GameInstall
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.common.retrofit.BiResponse
import com.gh.gamecenter.retrofit.RetrofitManager
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.MediaType
import okhttp3.RequestBody
import okhttp3.ResponseBody
import org.json.JSONArray
import org.json.JSONObject

class InstalledGameDialog(
    val mContext: Context,
    val games: ArrayList<GameInstall>,
    private val mEvent: String,
    private val mKey: String
) :
    TrackableDialog(mContext, R.style.DialogWindowTransparent, mEvent, mKey) {

    var onConfirmClickListener: (() -> Unit)? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding = DialogInstalledGameBinding.inflate(LayoutInflater.from(mContext), null, false)
        setContentView(binding.root)
        binding.dialogInstalledGameRv.apply {
            layoutManager = GridLayoutManager(context, 4)
            addItemDecoration(SpacingItemDecoration(bottom = 24F.dip2px()))
            adapter = InstalledGameAdapter(mContext, games)
        }
        binding.dialogCancel.setOnClickListener {
            MtaHelper.onEvent(mEvent, mKey, "点击取消")
            if (mEvent == "个人主页详情") {
                SPUtils.setBoolean(Constants.SP_MARK_INSTALLED_GAME_USER_HOME, true)
            } else {
                SPUtils.setBoolean(Constants.SP_MARK_INSTALLED_GAME_MY_GAME, true)
            }
            dismiss()
        }
        binding.dialogOk.setOnClickListener {
            debounceActionWithInterval(it.id, 2000L) {
                MtaHelper.onEvent(mEvent, mKey, "点击确定")
                if (mEvent == "个人主页详情") {
                    SPUtils.setBoolean(Constants.SP_MARK_INSTALLED_GAME_USER_HOME, true)
                } else {
                    SPUtils.setBoolean(Constants.SP_MARK_INSTALLED_GAME_MY_GAME, true)
                }
                postPlayedGames()
            }
        }
    }

    @SuppressLint("CheckResult")
    private fun postPlayedGames() {
        val objects = JSONArray()
        for (game in games) {
            val jsonObject = JSONObject()
            jsonObject.put("game_id", game.id)
            jsonObject.put("package", game.packageName)
            objects.put(jsonObject)
        }
        val requestBody = RequestBody.create(MediaType.parse("application/json"), objects.toString())
        RetrofitManager.getInstance().api
            .postPlayedGames(UserManager.getInstance().userId, requestBody)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BiResponse<ResponseBody>() {
                override fun onSuccess(data: ResponseBody) {
                    onConfirmClickListener?.invoke()
                    dismiss()
                }
            })
    }
}