package com.key.board.journey.inputmethod.keyboard

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.graphics.drawable.StateListDrawable
import android.util.Xml
import androidx.core.content.ContextCompat
import com.key.board.journey.inputmethod.MyKeyboard
import com.key.board.journey.inputmethod.R
import com.key.board.journey.inputmethod.keyboard.config.ConfigData
import com.key.board.journey.inputmethod.tools.keyboardTheme
import com.key.board.journey.inputmethod.tools.AllName
import com.key.board.journey.inputmethod.tools.Spstore
import org.xmlpull.v1.XmlPullParser
import java.io.File
import java.io.StringReader
import androidx.core.graphics.drawable.toDrawable

class ConfigMan(var context: Context) {


    private var textSize = 13f

    var functionDraw: Drawable =
        getDefaultDrawList(R.drawable.key_normal, R.drawable.key_presse)
    var generalDraw: Drawable =
        getDefaultDrawList(R.drawable.key_normal, R.drawable.key_presse)

    var toDraw: Drawable = getDefaultDrawList(R.drawable.key_normal, R.drawable.key_presse)
    var spaceDraw: Drawable = getDefaultDrawList(R.drawable.key_normal, R.drawable.key_presse)

//    var switchDraw: Drawable? = null
    var deleteDraw: Drawable? = null
    var backDraw: Drawable? = null
    var searchDraw: Drawable? = null

    var shiftDraw: Drawable? = null
    var shiftLockDraw: Drawable? = null

    var keyTextColor: Int = ContextCompat.getColor(context, R.color.white)
    var keyTextColorFunction: Int = ContextCompat.getColor(context, R.color.white)

    fun getConfig(): ConfigData? {
        val skinPath = Spstore.getSkinPath()
        val configFilePath = skinPath + "assets/keyboard.conf"
        val file = File(configFilePath)
        return if (file.exists()) {
            keyboardTheme.initConfig(configFilePath)
        } else {
            null
        }
    }

    fun getConfigBg(name: String): Drawable? {
        Spstore.getSkinPath()?.let { resPath ->
            val pPath = "${resPath}res/drawable-xhdpi-v4/"

            return getDrawList(
                pPath + name,
                pPath + name
            )
        }
        return null
    }

    fun updateSkinConfig() {
        Spstore.getSkinPath()?.let { resPath ->
            val pPath = "${resPath}res/drawable-xhdpi-v4/"
            pPath.let {
                readColors(resPath) {
                    for ((name, value) in it) {
                        if (name == AllName.keyTextColorName) {
                            keyTextColor = value
                        }
                        if (name == AllName.keyTextColorFunctionName) {
                            keyTextColorFunction = value
                        }
                    }

                }
                functionDraw = getDrawList(
                    it + AllName.functionNormalName,
                    it + AllName.functionPressName
                )
                generalDraw = getDrawList(it + AllName.normalName, it + AllName.pressName)
                toDraw = getDrawList(it + AllName.toNormalName, it + AllName.toPressName)
                spaceDraw =
                    getDrawList(it + AllName.spaceNormalName, it + AllName.spacePressName)
//                switchDraw =
//                    getDrawList(it + AllName.imeSwitchName, it + AllName.imeSwitchName)
                deleteDraw = getDrawList(
                    it + AllName.deleteNormalName,
                    it + AllName.deletePressName
                )
                backDraw = getDrawList(it + AllName.backName, it + AllName.backName)
                searchDraw = getDrawList(it + AllName.searchName, it + AllName.searchName)
                shiftDraw = getDrawList(
                    it + AllName.shiftNormalName,
                    it + AllName.shiftNormalName
                )
                shiftLockDraw =
                    getDrawList(it + AllName.shiftLockName, it + AllName.shiftLockName)
            }

        }
    }


    private fun getDefaultDrawList(normalDrawId: Int, pressDrawId: Int): StateListDrawable {
        val normalDraw = ContextCompat.getDrawable(MyKeyboard.myKeyboardInstance, normalDrawId)
        val pressDraw = ContextCompat.getDrawable(MyKeyboard.myKeyboardInstance, pressDrawId)
        val stateListDrawable = StateListDrawable().apply {
            addState(
                intArrayOf(android.R.attr.state_pressed),
                pressDraw
            )
            addState(intArrayOf(), normalDraw)
        }

        return stateListDrawable


    }


    private fun getDrawList(normalPath: String, pressPath: String): StateListDrawable {
        var normalDraw:Bitmap
        var pressDraw:Bitmap
        if(!File(normalPath).exists()){
            normalDraw =   BitmapFactory.decodeResource(MyKeyboard.myKeyboardInstance.resources, R.drawable.key_normal)
        }else{
            normalDraw = BitmapFactory.decodeFile(normalPath)
        }

        if(!File(pressPath).exists()){
            pressDraw =  BitmapFactory.decodeResource(MyKeyboard.myKeyboardInstance.resources, R.drawable.key_normal)
        }else{
            pressDraw = BitmapFactory.decodeFile(pressPath)
        }


        val stateListDrawable = StateListDrawable().apply {
            addState(
                intArrayOf(android.R.attr.state_pressed),
                pressDraw.toDrawable(context.resources)
            )
            addState(intArrayOf(), normalDraw.toDrawable(context.resources))
        }

        return stateListDrawable


    }

    private fun readColors(resPath: String, callBack: (Map<String, Int>) -> Unit) {
        val resMaps = mutableMapOf<String, Int>()

        val pPath = "${resPath}res/colors.xml"
        val file = File(pPath)
        if (file.exists()) {
            val xmlPullParser = Xml.newPullParser().apply {
                setInput(StringReader(file.readText()))
                setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false)

            }
            var curType = xmlPullParser.eventType
            while (curType != XmlPullParser.END_DOCUMENT) {
                val b = curType == XmlPullParser.START_TAG
                val b1 = xmlPullParser.name == "color"
                val b2 = xmlPullParser.name == "item"
                if (b && (b1 || b2)) {
                    val attributeName = xmlPullParser.getAttributeValue(null, "name")
                    val nextTextValue = xmlPullParser.nextText()
                    val b3 = attributeName == AllName.keyTextColorName
                    val b4 = attributeName == AllName.keyTextColorFunctionName
                    if (b3 || b4) {
                        resMaps[attributeName] = Color.parseColor(nextTextValue)
                    }
                }
                curType = xmlPullParser.next()
            }

        }

        callBack.invoke(resMaps)


    }


}