package com.base.scanqrclear.ui.spotifyqr

import android.app.Activity
import android.app.AlertDialog
import android.content.Intent
import android.text.Editable
import android.view.Gravity
import android.view.LayoutInflater
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.widget.addTextChangedListener
import com.base.scanqrclear.R
import com.base.scanqrclear.ads.AdsMgr
import com.base.scanqrclear.ads.AdsShowCallBack
import com.base.scanqrclear.bean.SpotifyUIBean
import com.base.scanqrclear.bean.SpotifyUIBean.Companion.createSpotifyQrString
import com.base.scanqrclear.databinding.DialogSpotifyBinding
import com.base.scanqrclear.qr.QrStyleActivity

object SpotifyDialog {

    fun Activity.showSpotifyDialog() {
        val dialog = AlertDialog.Builder(this).create()
        val binding = DialogSpotifyBinding.inflate(LayoutInflater.from(this))
        dialog.setView(binding.root)
        dialog.setCanceledOnTouchOutside(false)

        dialog.show()

        val params = dialog.window?.attributes
        params?.width = ConstraintLayout.LayoutParams.MATCH_PARENT
//        params?.height = resources.getDimensionPixelOffset(R.dimen.dp_400)
        params?.gravity = Gravity.BOTTOM
//        params?.y = 50

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

        AdsMgr.showNative(binding.flAd, R.layout.layout_admob_native_custom)

        binding.flClose.setOnClickListener {
            dialog.dismiss()
        }

        binding.editSingerName.addTextChangedListener { s: Editable? ->
            binding.tvBtn.isEnabled = !s.isNullOrEmpty() && !binding.editSong.text.isNullOrEmpty()
        }
        binding.editSong.addTextChangedListener { s: Editable? ->
            binding.tvBtn.isEnabled = !s.isNullOrEmpty() && !binding.editSingerName.text.isNullOrEmpty()
        }

        val jump = {
            dialog.dismiss()

            val singerName = binding.editSingerName.text.toString()
            val song = binding.editSong.text.toString()
            val bean = SpotifyUIBean(singerName, song)

            startActivity(Intent(this, QrStyleActivity::class.java).apply {
                putExtra(
                    "qrString", bean.createSpotifyQrString()
                )
            })
        }

        binding.tvBtn.setOnClickListener {

            AdsMgr.showInsert(this, false, object : AdsShowCallBack() {
                override fun close(where: Int) {
                    jump.invoke()
                }

                override fun failed(where: Int) {
                    jump.invoke()
                }

                override fun googleFailed(where: Int) {
                    jump.invoke()
                }
            })

        }

    }
}