package com.kaixed.kchat.ui.fragment


import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.kaixed.kchat.R
import com.kaixed.kchat.data.objectbox.ObjectBox.get
import com.kaixed.kchat.data.objectbox.entity.ChatLists
import com.kaixed.kchat.data.objectbox.entity.Messages
import com.kaixed.kchat.databinding.BottomSheetLayoutBinding
import com.kaixed.kchat.ui.activity.LoginActivity
import com.kaixed.kchat.utils.Constants.MMKV_USER_SESSION
import com.kaixed.kchat.utils.Constants.USER_LOGIN_STATUS
import com.tencent.mmkv.MMKV
import io.objectbox.BoxStore

/**
 * @Author: kaixed
 * @Date: 2024/10/29 13:45
 */
class MyBottomSheetFragment : BottomSheetDialogFragment() {

    private var _binding: BottomSheetLayoutBinding? = null
    private val binding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = BottomSheetLayoutBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(STYLE_NORMAL, R.style.MyBottomSheetDialogStyle)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        binding.tvQuitAccount.setOnClickListener {
            deleteAllUserData()
            activity?.finish()

            activity?.startActivity(
                Intent(
                    activity,
                    LoginActivity::class.java
                ).apply {
                    flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
                }
            )
        }

        binding.tvCancel.setOnClickListener {
            dismiss()
        }

        binding.tvQuitApp.setOnClickListener {
            activity?.finishAffinity()
        }

    }

    private fun deleteAllUserData() {
        val mmkv = MMKV.mmkvWithID(MMKV_USER_SESSION)
        mmkv.clearAll()

        MMKV.defaultMMKV().putBoolean(USER_LOGIN_STATUS, false)


        val boxStore: BoxStore = get()

        boxStore.boxFor(ChatLists::class.java).removeAll()
        boxStore.boxFor(Messages::class.java).removeAll()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}
