package com.photo.keyboard.themes.mykeyboard

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.inputmethodservice.Keyboard
import android.inputmethodservice.KeyboardView
import android.util.AttributeSet
import android.util.Log
import com.photo.keyboard.themes.manager.Utils
import com.photo.keyboard.themes.manager.ConstValue

@Suppress("DEPRECATION")
class MyCustomView @JvmOverloads constructor(
    var mContext: Context,
    attributeSet: AttributeSet? = null,
    style: Int = 0
) : KeyboardView(mContext, attributeSet, style) {
    var keyBoardManager = KeyBoardManager.myKeyBoardManager
    var shift_status = ConstValue.Shift_S
    var xmlMode = ConstValue.xml0

    private var mPaint: Paint = Paint().apply {
        isAntiAlias = true
        textAlign = Paint.Align.CENTER
        textSize = Utils.spToUnitPx(16f, mContext)
        color = keyBoardManager.keycolor
    }

    override fun onDraw(canvas: Canvas) {

        val config: com.photo.keyboard.themes.resconfig.KeyboardConfig? = keyBoardManager.getConfig()
        var keys: List<com.photo.keyboard.themes.resconfig.Key> = ArrayList<com.photo.keyboard.themes.resconfig.Key>()
        var i = 0

        for (curKey in keyboard.keys) {
            val code = curKey.codes[0]
            if (config != null) {
                if (code == 113 || code == 81 || code == 49 || code == 126) {
                    i = 0
                    val keyboardLayout: com.photo.keyboard.themes.resconfig.KeyboardLayout = config.getLayouts().get(0)
                    keys = keyboardLayout.getKeys()
                } else if (code == 97 || code == 65 || code == 64 || code == 163) {
                    i = 0
                    val keyboardLayout: com.photo.keyboard.themes.resconfig.KeyboardLayout = config.getLayouts().get(1)
                    keys = keyboardLayout.getKeys()
                } else if (code == -1 || code == -300 || code == -301) {
                    i = 0
                    val keyboardLayout: com.photo.keyboard.themes.resconfig.KeyboardLayout = config.getLayouts().get(2)
                    keys = keyboardLayout.getKeys()
                } else if (code == -2 || code == -102) {
                    i = 0
                    val keyboardLayout: com.photo.keyboard.themes.resconfig.KeyboardLayout = config.getLayouts().get(3)
                    keys = keyboardLayout.getKeys()
                }
                var background: String = keys[i].background + ".9.png"

                i++
                if (code == 32) {
                    config.keyList.forEach {
                        if(it.name.equals("KeySpace")){
                            background = "${it.background}.9.png"
                        }
                    }
                }
                Log.d("----TAG----", "-----code=${code}---background=${background}")
                val configBg: Drawable? = keyBoardManager.getConfigBg(mContext, background)
                if (configBg != null) {
                    Log.d("----TAG----", "--------background=1")
                    drawKeySuperTheme(configBg, canvas, code, curKey)
                } else {
                    drawKey(canvas, code, curKey)
                }


            } else {
                drawKey(canvas, code, curKey)
            }
        }


    }

    private fun drawKeySuperTheme(bgdraw: Drawable, canvas: Canvas, code: Int, key: Keyboard.Key) {
        key.let {
            when (code) {
                Keyboard.KEYCODE_SHIFT -> {
                    andDraw(
                        it,
                        bgdraw,
                        getCurIc(),
                        canvas
                    )
                }

                ConstValue.SHIFT_NUMBER, ConstValue.SHIFT_SYMBOL -> {
                    andDraw(it, bgdraw, null, canvas)
                }

                Keyboard.KEYCODE_DELETE -> {
                    andDraw(
                        it,
                        bgdraw,
                        keyBoardManager.icDel,
                        canvas
                    )
                }

                Keyboard.KEYCODE_MODE_CHANGE, Keyboard.KEYCODE_DONE -> {
                    andDraw(it, bgdraw, null, canvas)
                }

                else -> {
                    andDraw(it, bgdraw, null, canvas)
                }
            }
        }

    }

    private fun drawKey(canvas: Canvas, code: Int, key: Keyboard.Key) {
        key.let {
            when (code) {
                32->{
                    andDraw(it, keyBoardManager.spBackgroundDraw, null, canvas)
                }
                Keyboard.KEYCODE_SHIFT -> {
                    andDraw(
                        it,
                        keyBoardManager.functionBackgroundDraw,
                        getCurIc(),
                        canvas
                    )
                }

                ConstValue.SHIFT_NUMBER, ConstValue.SHIFT_SYMBOL -> {
                    andDraw(it, keyBoardManager.functionBackgroundDraw, null, canvas)
                }

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

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

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

    }

    fun upUi(con: Context) {
        keyBoardManager.uodateConfig(con)
        background = keyBoardManager.allBg
        invalidate()

    }

    private fun getCurIc(): Drawable? {
        return when (shift_status) {
            ConstValue.Shift_B_lo -> keyBoardManager.icShittLock
            ConstValue.Shift_B -> keyBoardManager.icBshift
            ConstValue.Shift_S -> keyBoardManager.icSshift
            else -> keyBoardManager.icSshift
        }
    }


    @SuppressLint("SuspiciousIndentation")
    private fun andDraw(
        myKey: Keyboard.Key,
        keyBG: Drawable,
        icon: Drawable?,
        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()
                var icon_wr = icon_w / myKey.width.toFloat()
                var icon_h = myKey.icon.intrinsicHeight.toFloat()
                var 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)
                }
            }

            mPaint.color = keyBoardManager.keycolor
            if (!label.isNullOrEmpty()) {
                val y1 = y.plus(paddingRight).plus((height.div(2f)))
                    .plus((mPaint.textSize.minus(mPaint.descent())).div(2f))
                val x1 = x.plus(paddingLeft).plus((width.div(2f)))
                canvas.drawText(label.toString(), x1, y1, mPaint)
            }
        }


    }
}