package com.qmai.android.keyboard;

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.inputmethodservice.Keyboard
import android.inputmethodservice.KeyboardView
import android.util.AttributeSet
import android.util.Log
import android.util.TypedValue
import android.widget.EditText
import com.qmai.android.keyboardview.R

/**
 *   created by wangwei   ON 6/12/20  email:wangwei_5521@163.com
 *   @version 1.1.1  指定大小的
 **/
@Suppress("DEPRECATION")
class ExactSizeMoneyNumberKeyBoardKeyBoard : KeyboardView {
    private lateinit var keys: List<Keyboard.Key>
    private var editWidget: EditText? = null
    private lateinit var mtextPaint: Paint
    public var btnText = "结账"
    //获取drawable资源
    val drawable = context.resources.getDrawable(R.drawable.savestock)

    private var defaultActionListener: DefaultKeyBoardActionListener? =
        DefaultKeyBoardActionListener()

    enum class Code constructor(var code: Int) {
        DELETE(10), CLEAR(11), SAVE(-11)
    }

    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {
        init(context)
    }

    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {

        init(context)
    }


    fun bindEditText(editText: EditText?) {
        editWidget = editText
        defaultActionListener?.et = editText
    }

    fun setKeyBoardLister(keyBoardListener: DefaultKeyBoardActionListener?) {
        defaultActionListener = keyBoardListener
        onKeyboardActionListener = defaultActionListener
    }

    @SuppressLint("UseCompatLoadingForDrawables")
    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        if (!::keys.isInitialized){
            keys = getKeyboard().keys
        }




        canvas?.let { c ->
            val keys: List<Keyboard.Key> = keyboard.keys
            keys.forEach { key ->
                Log.d(TAG, "onDraw: height= $height key height= ${key.height} x= ${key.x} y= ${key.y}" )
                if (key.codes[0] == -11) {


                    //把真正的状态设置给上层绘制的key键
                    drawable.state = key.currentDrawableState
                    //rawable将在被绘制在canvas的哪个矩形区域内（这个矩形区域的坐标是以canvas左上角为坐标原点的）
                    drawable.setBounds(
                        key.x,
                        key.y + paddingTop,
                        key.x + key.width + 2,
                        key.y + key.height + 4
                    )
                    //开始绘制
                    drawable.draw(canvas)
                    if (key.label != null) {
                        val rect = Rect(key.x,key.y, (key.x + key.width), (key.y + key.height))
                        val fontMetrics = mtextPaint.fontMetrics
                        val top = fontMetrics.top;//为基线到字体上边框的距离,即上图中的top
                        val bottom = fontMetrics.bottom;//为基线到字体下边框的距离,即上图中的bottom

                        val baseLineY = (rect.centerY() - top/2 - bottom/2)

                        /*   //计算基线
                           val baseLine =
                               key.y + (key.height) / 2 - (fontMetrics.bottom - fontMetrics.top) / 2- fontMetrics.bottom*/
                        //绘制文字
                        canvas.drawText(
                            btnText,
                            rect.centerX().toFloat(), baseLineY, mtextPaint
                        )
                    }
                } else if (key.codes[0] == 10) {
                    val drawable = context.resources.getDrawable(R.drawable.delete)
                    //把真正的状态设置给上层绘制的key键
                    drawable.state = key.currentDrawableState
                    //rawable将在被绘制在canvas的哪个矩形区域内（这个矩形区域的坐标是以canvas左上角为坐标原点的）
                    drawable.setBounds(
                        0,0,key.width,key.height
                    )
                    canvas.save()
                    canvas.translate((key.x + paddingLeft).toFloat(),
                        (key.y + paddingTop).toFloat()
                    )
                    //开始绘制
                    drawable.draw(canvas)
                    canvas.restore()
                    if (key.icon != null) {
                        key.icon.setBounds(
                            (key.x + key.width / 2) - key.icon.intrinsicWidth / 2,
                            key.y + key.height / 2 - key.icon.intrinsicHeight / 2,
                            key.x + key.width / 2 + key.icon.intrinsicWidth / 2,
                            key.y + key.height / 2 + key.icon.intrinsicHeight / 2
                        )
                        //开始绘制
                        key.icon.draw(canvas)
                    }
                }
            }
        }
    }


    open class DefaultKeyBoardActionListener : OnKeyboardActionListener {

        var et: EditText? = null

        override fun swipeRight() {

        }

        override fun onPress(primaryCode: Int) {

        }

        override fun onRelease(primaryCode: Int) {

        }

        override fun swipeLeft() {

        }

        override fun swipeUp() {

        }

        override fun swipeDown() {

        }

        override fun onKey(primaryCode: Int, keyCodes: IntArray?) {
            et ?: return
            val editable = et!!.editableText
            when (primaryCode) {
                Code.CLEAR.code -> {
                    editable.clear()
                }
                Code.DELETE.code -> {
                    if (editable.isNotEmpty()) {
                        editable.delete(editable.length - 1, editable.length)
                    }
                }
                20 -> {
                    editable.append(".")
                }
                21 -> {
                    editable.append("00")
                }
                Code.SAVE.code -> {
                }
                else -> {
                    editable.append(primaryCode.toString())
                }
            }


        }

        override fun onText(text: CharSequence?) {

        }

    }
    @SuppressLint("DrawAllocation")
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        val keyBoard = Keyboard(context, R.xml.exact_size_moneykeyboard,0,MeasureSpec.getSize(widthMeasureSpec),MeasureSpec.getSize(heightMeasureSpec))
        this.keyboard = keyBoard
        keys = getKeyboard().keys
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)

    }

    private fun init(context: Context?) {

        isEnabled = true
        isPreviewEnabled = false
        onKeyboardActionListener = defaultActionListener
        mtextPaint = Paint(Paint.ANTI_ALIAS_FLAG)
        mtextPaint.textAlign = Paint.Align.CENTER
        mtextPaint.textSize = sp2px(20f)
        mtextPaint.color = Color.parseColor("#333333")

    }

    private fun sp2px(spValue: Float): Float {
        return TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_SP,
            spValue,
            resources.displayMetrics
        )
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()

        Log.d("TAG", "onDetachedFromWindow: ")
    }
    companion object{
        private const val TAG = "MoneyNumberKeyBoardKeyB"
    }
}