package com.sunny.app.soft.timberkeyboardnew.ui.view

import android.annotation.SuppressLint
import android.content.Context
import android.content.SharedPreferences
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.graphics.drawable.StateListDrawable
import android.inputmethodservice.Keyboard
import android.inputmethodservice.KeyboardView
import android.util.AttributeSet
import android.util.Log
import android.view.inputmethod.EditorInfo
import androidx.core.content.ContextCompat
import com.sunny.app.soft.timberkeyboardnew.App
import com.sunny.app.soft.timberkeyboardnew.R
import com.sunny.app.soft.timberkeyboardnew.tools.AppConstant
import com.sunny.app.soft.timberkeyboardnew.tools.ZipTools
import java.io.File


@Suppress("DEPRECATION")
class MyKeyboardView @JvmOverloads constructor(
    var myContext: Context,
    attributeSet: AttributeSet? = null,
    style: Int = 0
) : KeyboardView(myContext, attributeSet, style) {

    private var curimeAction = EditorInfo.IME_ACTION_UNSPECIFIED


    inner class MyConfig {
        lateinit var functionBackgroundDraw: Drawable
        lateinit var spBackgroundDraw: Drawable
        lateinit var normalBackgroundDraw: Drawable
        var icShittLock: Drawable? =
            ContextCompat.getDrawable(context, R.drawable.svg_shift)
        var icDel: Drawable? =
            ContextCompat.getDrawable(context, R.drawable.svg_delete)
        var allBg: Drawable? =
            ContextCompat.getDrawable(context, R.mipmap.main_bg)
        var icBshift: Drawable? =
            ContextCompat.getDrawable(context, R.drawable.svg_shift)
        var icSshift: Drawable? =
            ContextCompat.getDrawable(context, R.drawable.svg_shift)

        var icEnter: Drawable? =
            ContextCompat.getDrawable(context, R.drawable.key_ic_enter)

        var icSearch: Drawable? =
            ContextCompat.getDrawable(context, R.drawable.key_ic_search)

        var keycolor: Int = context.resources.getColor(R.color.white33, null)

        private val sp: SharedPreferences = context.getSharedPreferences(
            AppConstant.SHARE_NAME,
            Context.MODE_PRIVATE
        )

        private fun getbgic(con: Context, filePath: String): Drawable? {
            if (!File(filePath).exists()) {
                return null
            }
            return BitmapDrawable(con.resources, BitmapFactory.decodeFile(filePath))
        }

        private fun getStatus(draw: Drawable, drawPress: Drawable): StateListDrawable {
            return StateListDrawable().apply {
                addState(intArrayOf(android.R.attr.state_pressed), drawPress)
                addState(intArrayOf(), draw)
            }
        }


        private fun gettextcolornew(filePath: String) {
            if (File(filePath).exists()) {
                val decodeFile = BitmapFactory.decodeFile(filePath)
                val pixelColor: Int = decodeFile.getPixel(0, 0)
                val red = Color.red(pixelColor)
                val green = Color.green(pixelColor)
                val blue = Color.blue(pixelColor)

                keycolor = Color.rgb(red, green, blue)

            }
        }

        init {
            val default =
                ContextCompat.getDrawable(context, R.drawable.png_keybg)
            val press = ContextCompat.getDrawable(
                context,
                R.drawable.png_keybg_press
            )
            if (press != null) {
                if (default != null) {
                    val listDrawable = getStatus(default, press)
                    functionBackgroundDraw = listDrawable
                    normalBackgroundDraw = listDrawable
                    spBackgroundDraw = listDrawable
                }
            }
        }

        fun updateConfig(con: Context) {
            sp.getString(AppConstant.KEY_CUR_Skin_Number, "")?.let { skin_Number ->
                val unzipPath = ZipTools.getUnzipPath(skin_Number) + "/"
                val style = sp.getInt(AppConstant.KEY_CUR_STYLE, 1)
                Log.d(App.TAG, "------updateConfig----skin_Number =  $skin_Number style=${style} ")

                gettextcolornew(unzipPath.plus(AppConstant.getTextColor(skin_Number, style)))

                getbgic(
                    con,
                    unzipPath.plus(AppConstant.getnormalBg(skin_Number, style))
                )?.let { drawBG ->
                    normalBackgroundDraw = getStatus(drawBG, drawBG)
                }
                getbgic(con, unzipPath.plus(AppConstant.getSpaceBg(skin_Number)))?.let { drawBG ->
                    spBackgroundDraw = getStatus(drawBG, drawBG)
                }

                sp.getString(AppConstant.KEY_CUR_Bg, "")?.run {
                    //file:///android_asset/Abstract/photo_24055_89_44_1654593252.png
                    val replace = this.replace("file:///android_asset/", "")
                    val loadDrawableFromAsset = ZipTools.loadDrawableFromAsset(replace)
                    loadDrawableFromAsset?.let {
                        allBg = it
                        Log.d(App.TAG, "------updateConfig----allBg  ")
                    }
                }


                // ok
                getbgic(
                    con,
                    unzipPath.plus(AppConstant.getnormalBg(skin_Number, style))
                )?.let { drawBG ->
                    functionBackgroundDraw = getStatus(drawBG, drawBG)

                }


                // ok
                getbgic(con, unzipPath.plus(AppConstant.getCaps(skin_Number)))?.let {
                    icSshift = it
                    icBshift = it
                }


                getbgic(
                    con,
                    unzipPath.plus(AppConstant.getDeleteRes(skin_Number))
                )?.let { drawBG ->
                    icDel = getStatus(drawBG, drawBG)
                }


                getbgic(con, unzipPath.plus(AppConstant.getCapsenable(skin_Number)))?.let {
                    icShittLock = it
                }

                getbgic(con, unzipPath.plus(AppConstant.getEnterIcon(skin_Number)))?.let {
                    icEnter = it
                }

            }
        }
    }

    var config = MyConfig()
    var shiftStatus = AppConstant.Shift_S
    var xmlMode = AppConstant.xml0

    private var myPaint: Paint = Paint().apply {
        isAntiAlias = true
        textAlign = Paint.Align.CENTER
        textSize = myContext.resources.displayMetrics.scaledDensity * 16f
        color = config.keycolor
    }

    @SuppressLint("SuspiciousIndentation")
    private fun andDraw(
        myKey: Keyboard.Key,
        keyBG: Drawable,
        icon: Drawable?,
        customerLabel: String? = null,
        canvas: Canvas,
    ) {
        myKey.run {
            keyBG.run {
                bounds = Rect(
                    x.plus(paddingLeft),
                    y.plus(paddingTop),
                    width.plus(x.plus(paddingLeft)),
                    height.plus(y.plus(paddingTop))
                )
                state = currentDrawableState
                draw(canvas)
            }
        }

        myKey.run {
            icon?.apply {
                myKey.icon = this

                var icon_w = myKey.icon.intrinsicWidth.toFloat()
                val icon_wr = icon_w / myKey.width.toFloat()
                var icon_h = myKey.icon.intrinsicHeight.toFloat()
                val icon_hr = icon_h / myKey.height.toFloat()


                var tep1 = 0f
                var tep2 = 0f
                if (icon_wr > icon_hr) {
                    tep2 = icon_wr
                    tep1 = icon_wr.coerceAtLeast(0.5f)

                } else {
                    tep2 = icon_hr
                    tep1 = icon_hr.coerceAtLeast(0.5f)

                }
                icon_h = (icon_h / tep2) * tep1
                icon_w = (icon_w / tep2) * tep1
                myKey.icon.let {
                    it.bounds = Rect().apply {

                        top =
                            (myKey.y + paddingTop + (myKey.height - icon_h) / 2f).toInt()
                        left =
                            (myKey.x + paddingLeft + (myKey.width - icon_w) / 2f).toInt()
                        bottom = (top + icon_h).toInt()
                        right = (left + icon_w).toInt()

                    }
                    it.draw(canvas)
                }
            }

            myPaint.color = config.keycolor

            val y1 = y.plus(paddingRight).plus((height.div(2f)))
                .plus((myPaint.textSize.minus(myPaint.descent())).div(2f))
            val x1 = x.plus(paddingLeft).plus((width.div(2f)))
            customerLabel?.let {
                myPaint.textSize = myContext.resources.displayMetrics.scaledDensity * 13f
                canvas.drawText(it, x1, y1, myPaint)
            }.run {
                if (!label.isNullOrEmpty()) {
                    myPaint.textSize = myContext.resources.displayMetrics.scaledDensity * 16f
                    canvas.drawText(label.toString(), x1, y1, myPaint)
                }
            }

        }
    }

    private fun getCurIc(): Drawable? {
        return when (shiftStatus) {
            AppConstant.Shift_B_lo -> config.icShittLock
            AppConstant.Shift_B -> config.icBshift
            AppConstant.Shift_S -> config.icSshift
            else -> config.icSshift
        }
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        keyboard.keys.forEach {
            when (it.codes[0]) {
                Keyboard.KEYCODE_SHIFT -> {
                    andDraw(
                        it,
                        config.functionBackgroundDraw,
                        getCurIc(),
                        null,
                        canvas
                    )
                }

                AppConstant.SHIFT_NUMBER, AppConstant.SHIFT_SYMBOL -> {
                    andDraw(it, config.functionBackgroundDraw, null,null, canvas)
                }

                Keyboard.KEYCODE_DELETE -> {
                    andDraw(
                        it,
                        config.functionBackgroundDraw,
                        config.icDel,null,
                        canvas
                    )
                }

                Keyboard.KEYCODE_MODE_CHANGE -> {
                    andDraw(
                        it,
                        config.functionBackgroundDraw,
                        null,null,
                        canvas
                    )
                }

                AppConstant.KEY_CODE_SPACE -> {
                    andDraw(it, config.spBackgroundDraw, null,null, canvas)
                }

                Keyboard.KEYCODE_DONE -> {
                    when (curimeAction) {
//                        EditorInfo.IME_ACTION_NONE -> {
//                            Log.d(App.TAG, "=======NONE")
//                            andDraw(it, config.functionBackgroundDraw, config.icEnter,null, canvas)
//                        }
//                        EditorInfo.IME_ACTION_GO -> {
//
//                            Log.d(App.TAG, "=======go")
//                            andDraw(it, config.functionBackgroundDraw,null,"Go", canvas)
//                        }
                        EditorInfo.IME_ACTION_SEARCH -> {
                            Log.d(App.TAG, "=======SEARCH")
                            andDraw(it, config.functionBackgroundDraw, null,"Search", canvas)
                        }
//                        EditorInfo.IME_ACTION_SEND -> {
//                            Log.d(App.TAG, "=======SEND")
//                            andDraw(it, config.functionBackgroundDraw,null,"Send", canvas)
//                        }
//                        EditorInfo.IME_ACTION_NEXT -> {
//                            Log.d(App.TAG, "=======NEXT")
//                            andDraw(it, config.functionBackgroundDraw,null,"Next", canvas)
//                        }
//                        EditorInfo.IME_ACTION_DONE -> {
//                            Log.d(App.TAG, "=======DONE")
//                            andDraw(it, config.functionBackgroundDraw,null,"Done", canvas)
//                        }
//                        EditorInfo.IME_ACTION_PREVIOUS -> {
//                            Log.d(App.TAG, "=======PREVIOUS")
//                            andDraw(it, config.functionBackgroundDraw,null,"Previous", canvas)
//                        }
                        else -> {
                            Log.d(App.TAG, "=======else")
                            andDraw(it, config.functionBackgroundDraw,null,"Done", canvas)
                        }
                    }

                }


                else -> {
                    andDraw(it, config.normalBackgroundDraw, null, null,canvas)
                }
            }
        }
    }

    fun upUi(con: Context, ime: Int) {
        curimeAction = ime
        config.updateConfig(con)
        background = config.allBg
        invalidate()
    }

}