package com.keyboard.journey

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.BitmapFactory
import android.graphics.Color
import android.graphics.drawable.BitmapDrawable
import android.os.Bundle
import android.provider.Settings
import android.view.View
import android.view.inputmethod.InputMethodManager
import androidx.appcompat.app.AppCompatActivity
import com.gyf.immersionbar.ktx.immersionBar
import com.keyboard.journey.databinding.JourneyPreviewActivityBinding
import com.keyboard.journey.util.currentlyThemeUFileString
import com.keyboard.journey.util.getBitmapXXDrawable
import com.keyboard.journey.util.isMyInputMethodDefault
import com.keyboard.journey.util.isMyInputMethodEnabled
import com.keyboard.journey.util.loadAndBlurImage

class PreviewActivity : AppCompatActivity() {
    companion object {
        const val KEY_PREVIEW_URL = "key_preview_url"
    }

    private lateinit var binding: JourneyPreviewActivityBinding

    private var themeUrl = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = JourneyPreviewActivityBinding.inflate(layoutInflater)
        setContentView(binding.root)

        initBar()
        themeUrl = intent.getStringExtra(KEY_PREVIEW_URL).toString()
        registerReceiver()
        initView()
    }

    private fun initBar() {
        immersionBar {
            statusBarDarkFont(true)
            fitsSystemWindows(true)
        }
    }

    override fun onResume() {
        super.onResume()
        updateSetMyInputMethod()
    }

    override fun onBackPressed() {
        super.onBackPressed()
        // TODO: showAd
    }

    private fun initView() {
        val currentlyThemeUFile = currentlyThemeUFileString(this, themeUrl)
        loadAndBlurImage(
            this,
            getBitmapXXDrawable(this, currentlyThemeUFile, "keyboard_preview_screenshot.jpg"),
            binding.previewIv
        )

        val imagePath =
            "$currentlyThemeUFile/res/drawable-xxhdpi-v4/keyboard_preview.jpg"
        val bitmap = BitmapFactory.decodeFile(imagePath)
        val background = BitmapDrawable(resources, bitmap)
        binding.keyboardIv.background = background

        binding.backBtn.setOnClickListener { onBackPressed() }

        binding.activateBtn.setOnClickListener {
            binding.dialogStepLayout.visibility = View.VISIBLE
        }

        binding.step1Btn.setOnClickListener {
            val intent = Intent(Settings.ACTION_INPUT_METHOD_SETTINGS)
            startActivity(intent)
        }

        binding.step2Btn.setOnClickListener {
            val imeManager = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
            imeManager.showInputMethodPicker()
        }

        binding.dialogStepLayout.setOnClickListener {
            binding.dialogStepLayout.visibility = View.GONE
        }
    }

    private fun updateSetMyInputMethod() {
        val enabled = isMyInputMethodEnabled(this)
        val default = isMyInputMethodDefault(this)
        if (enabled) {
            binding.step1Btn.background = getDrawable(R.drawable.drw_gray_select_bg)
            binding.step1Btn.text = "Step 1:Enabled"
            binding.step1Btn.setTextColor(Color.parseColor("#999999"))
        } else {
            binding.step1Btn.background = getDrawable(R.mipmap.activate_btn_bg)
            binding.step1Btn.text = "Step 1:Select"
            binding.step1Btn.setTextColor(Color.parseColor("#000000"))
        }
        if (default) {
            binding.step2Btn.background = getDrawable(R.drawable.drw_gray_select_bg)
            binding.step2Btn.text = "Step 2:Enabled"
            binding.step1Btn.setTextColor(Color.parseColor("#999999"))
        } else {
            binding.step2Btn.background = getDrawable(R.mipmap.activate_btn_bg)
            binding.step2Btn.text = "Step 2:Select"
            binding.step1Btn.setTextColor(Color.parseColor("#000000"))
        }

        if (enabled && default) {
            binding.edit.visibility = View.VISIBLE
            binding.tv.visibility = View.GONE
        } else {
            binding.edit.visibility = View.GONE
            binding.tv.visibility = View.VISIBLE
        }

        if (enabled && default) {
            binding.unauthorizedLayout.visibility = View.INVISIBLE

            showKeyboard(binding.edit)
        }
    }

    private var receiver: BroadcastReceiver? = null
    private fun registerReceiver() {
        val filter = IntentFilter(Intent.ACTION_INPUT_METHOD_CHANGED)
        receiver = object : BroadcastReceiver() {
            override fun onReceive(context: Context, intent: Intent) {
                updateSetMyInputMethod()
                val enabled = isMyInputMethodEnabled(this@PreviewActivity)
                val default = isMyInputMethodDefault(this@PreviewActivity)
                if (enabled && default) {
                    binding.dialogStepLayout.visibility = View.GONE
                    binding.edit.visibility = View.VISIBLE
                    binding.tv.visibility = View.GONE
                    showKeyboard(binding.edit)
                } else {
                    binding.dialogStepLayout.visibility = View.VISIBLE
                }
            }
        }
        registerReceiver(receiver, filter)
    }

    private fun unregisterReceiver() {
        if (receiver != null) {
            unregisterReceiver(receiver)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver()
    }

    private fun showKeyboard(view: View) {
        view.postDelayed({
            view.requestFocus()
            val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
        }, 1000) // 设置延迟时间


    }
}