package com.base.scanqr.ui.widget

import android.app.AlertDialog
import android.content.Context
import android.view.Gravity
import android.view.LayoutInflater
import com.base.scanqr.R
import com.base.scanqr.databinding.DialogSortByBinding
import com.base.scanqr.ui.main.HistoryFragment.Companion.SORT_NAME
import com.base.scanqr.ui.main.HistoryFragment.Companion.SORT_TIME
import com.base.scanqr.ui.main.HistoryFragment.Companion.SORT_TYPE
import com.base.scanqr.ui.main.HistoryFragment.Companion.aesOrDes
import com.base.scanqr.ui.main.HistoryFragment.Companion.sortType

object SortByDialog {


    fun Context.showSortByDialog(dismissAction: () -> Unit) {
        val dialog = AlertDialog.Builder(this).create()
        val binding = DialogSortByBinding.inflate(LayoutInflater.from(this))
        dialog.setView(binding.root)
        dialog.setCanceledOnTouchOutside(false)

        dialog.show()

        val params = dialog.window?.attributes
//        params?.width = resources.getDimensionPixelOffset(R.dimen.dp_320)
//        params?.height = resources.getDimensionPixelOffset(R.dimen.dp_400)
        params?.gravity = Gravity.CENTER
//        params?.y = 50

        dialog.window?.attributes = params
        dialog.window?.setBackgroundDrawableResource(android.R.color.transparent)

        when (sortType) {
            SORT_NAME -> {
                binding.rg.check(R.id.rbName)
            }

            SORT_TIME -> {
                binding.rg.check(R.id.rbTime)
            }

            SORT_TYPE -> {
                binding.rg.check(R.id.rbType)
            }
        }
        binding.rg.setOnCheckedChangeListener { group, checkedId ->
            when (checkedId) {
                R.id.rbName -> {
                    sortType = SORT_NAME
                }

                R.id.rbTime -> {
                    sortType = SORT_TIME
                }

                R.id.rbType -> {
                    sortType = SORT_TYPE
                }
            }

        }
        binding.tvAscending.setOnClickListener {
            dialog.dismiss()
            aesOrDes = true
        }
        binding.tvDescending.setOnClickListener {
            dialog.dismiss()
            aesOrDes = false
        }
        dialog.setOnDismissListener {
            dismissAction.invoke()
        }
    }
}