package com.qmai.android.keyboard;

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.*
import android.inputmethodservice.Keyboard
import android.inputmethodservice.KeyboardView
import android.text.Layout
import android.text.StaticLayout
import android.text.TextPaint
import android.util.AttributeSet
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
 **/
class StockNumberKeyBoardKeyBoard : KeyboardView {

    private lateinit var editWidget: EditText
    private lateinit var mtextPaint: TextPaint

    private var defaultActionListener = DefaultKeyBoardActionListener()

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

    public var btnText = "保存"


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

    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        val array = context?.obtainStyledAttributes(attrs, R.styleable.keyBoardText)
        array?.let {

        }
        init(context)
    }


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

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

    @SuppressLint("DrawAllocation")
    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        canvas?.let { c ->
            val keys: List<Keyboard.Key> = keyboard.keys
            keys.forEach { key ->
                if (key.codes[0] == -11) {

                    //获取drawable资源
                    val drawable = context.resources.getDrawable(R.drawable.savestock)
                    //把真正的状态设置给上层绘制的key键
                    drawable.state = key.currentDrawableState
                    //rawable将在被绘制在canvas的哪个矩形区域内（这个矩形区域的坐标是以canvas左上角为坐标原点的）
                    drawable.setBounds(
                        key.x,
                        key.y + paddingTop,
                        key.x + key.width + paddingRight,
                        key.y + key.height + 4
                    )
                    //开始绘制
                    drawable.draw(canvas)
                    if (key.label != null) {


                        canvas.save()
                        val actualText = btnText.replace("\n", "")
                        val rect = Rect()
                        mtextPaint.getTextBounds(actualText, 0, actualText.length, rect)
                        val singleTextHeight = rect.height()
                        val singleTextWidth = rect.width() / actualText.length
                        val allHeight = singleTextHeight * actualText.length
                        val fontMetrics = mtextPaint.fontMetrics
                        //计算基线
                        val baseLine =
                            key.y + (key.height + paddingBottom) / 2 - (fontMetrics.bottom - fontMetrics.top) / 2

                        val layout = StaticLayout(
                            btnText, mtextPaint, singleTextWidth - 10,
                            Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, true
                        )
                        canvas.save()
                        canvas.translate(
                            (key.x + ((key.width + paddingRight) / 2)).toFloat(),
                            baseLine - allHeight / 2 - singleTextHeight
                        )
                        layout.draw(canvas)
                        canvas.restore()
                        mtextPaint.measureText(btnText)

                        //绘制文字
                        /* canvas.drawText(
                             btnText,
                             (key.x + ((key.width + paddingRight) / 2)).toFloat(),
                             baseLine,
                             mtextPaint
                         )*/

                    }
                }
            }
        }
    }


    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)
                    }
                }
                Code.SAVE.code -> {
                }
                else -> {
                    editable.append(primaryCode.toString())
                }
            }


        }

        override fun onText(text: CharSequence?) {

        }

    }

    private fun init(context: Context?) {
        val keyBoard = Keyboard(context, R.xml.stockkeyboard)
        isEnabled = true
        isPreviewEnabled = false
        this.keyboard = keyBoard
        onKeyboardActionListener = defaultActionListener
        mtextPaint = TextPaint(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
        )
    }

}