package hxd.cn.sweepapp.activity

import android.annotation.SuppressLint
import android.content.DialogInterface
import android.graphics.Typeface
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Toast
import hxd.cn.sweepapp.R
import hxd.cn.sweepapp.info.FUNCTIONCODE
import hxd.cn.sweepapp.info.MODECODE
import hxd.cn.sweepapp.utils.Tools
import hxd.cn.sweepapp.utils.ZxingUtils
import kotlinx.android.synthetic.main.activity_main.*


class MainActivity : AppCompatActivity(), AdapterView.OnItemSelectedListener, View.OnClickListener {


    lateinit var typeface: Typeface
    lateinit var mode: Array<String>
    lateinit var modeValueArray: Array<String>
    lateinit var functionArray: Array<String>
    lateinit var functionValueArray: Array<String>
    lateinit var keyArray: Array<String>
    lateinit var addrArray: ArrayList<String>
    lateinit var items: ArrayList<String>

    var itemsa = arrayOf("100模式", "1000模式", "10模式")

    lateinit var functionValue: String
    lateinit var modeValue: String
    lateinit var addrValue: String
    lateinit var keyValue: String

    lateinit var addrs: String
    var isSettingScannerGun = false


    var handler: Handler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message?) {
            when (msg!!.what) {
                FUNCTIONCODE -> {
                    if (isSettingScannerGun) {
                        functionValue = "53540D" + Tools.setScannerGun() + Tools.getXor("53540D" + Tools.setScannerGun())
                    }
                    image_code.setImageBitmap(ZxingUtils.Create2DCode(functionValue, 200, 200))
                }
                MODECODE -> {
                    tv_msg.setText(QRCode)
                    image_code.setImageBitmap(ZxingUtils.Create2DCode(QRCode, 200, 200))
                }
            }

            super.handleMessage(msg)
        }
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        bindView()
    }

    @SuppressLint("ResourceAsColor")
    fun bindView() {
        items = arrayListOf("100模式", "1000模式", "10模式")
        typeface = Typeface.createFromAsset(this.assets, "fonts/Eurostile LT Demi.ttf")
        bt01.typeface = typeface
        bt02.typeface = typeface
        tip01.setTypeface(typeface, Typeface.ITALIC)
        tip02.setTypeface(typeface, Typeface.ITALIC)
        mode = resources.getStringArray(R.array.modes)
        keyArray = resources.getStringArray(R.array.key)
        functionArray = resources.getStringArray(R.array.function)

        functionValueArray = resources.getStringArray(R.array.function_value)
        modeValueArray = resources.getStringArray(R.array.modes_value)
        functionValue = functionValueArray[0]
        modeValue = modeValueArray[0]

        addrArray = ArrayList()
        for (i in 0..255) {
            if (String.format("%X", i).length == 1) {
                addrArray.add("0" + String.format("%X", i))
            } else {
                addrArray.add(String.format("%X", i))
            }
        }

        var deviceAdapter = ArrayAdapter<String>(this, R.layout.spinner_default_item, mode)
        deviceAdapter.setDropDownViewResource(R.layout.spinner_item)
        spinner_working_mode.adapter = deviceAdapter
        deviceAdapter = ArrayAdapter<String>(this, R.layout.spinner_default_item, functionArray)
        deviceAdapter.setDropDownViewResource(R.layout.spinner_item)
        spinner_function_list.adapter = deviceAdapter
        deviceAdapter = ArrayAdapter<String>(this, R.layout.spinner_default_item, addrArray)
        deviceAdapter.setDropDownViewResource(R.layout.spinner_item)
        spinner_memory_addr.adapter = deviceAdapter
        deviceAdapter = ArrayAdapter<String>(this, R.layout.spinner_default_item, keyArray)
        deviceAdapter.setDropDownViewResource(R.layout.spinner_item)
        spinner_key.adapter = deviceAdapter
        spinner_function_list.setOnItemSelectedListener(this)
        spinner_working_mode.setOnItemSelectedListener(this)
        spinner_memory_addr.setOnItemSelectedListener(this)
        spinner_key.setOnItemSelectedListener(this)
        bt01.setOnClickListener(this)
        bt02.setOnClickListener(this)
    }


    fun singleChoice() {
        val builder = AlertDialog.Builder(this)
                // 设置对话框标题
                .setTitle("单选列表项对话框")
                // 设置图标
                .setIcon(R.mipmap.andorid)
                // 设置单选列表项，默认选中第二项（索引为1）
                .setSingleChoiceItems(itemsa, 1, DialogInterface.OnClickListener { dialog, which ->
                    //show.setText("你选中了《" + items[which] + "》")
                })
        // 为AlertDialog.Builder添加“确定”按钮
        setPositiveButton(builder)
        // 为AlertDialog.Builder添加“取消”按钮
        setNegativeButton(builder)
                .create()
                .show()
    }

    lateinit var QRCode: String
    override fun onClick(p0: View?) {
        when (p0!!.id) {
            R.id.bt01 -> {
                //    singleChoice()
                handler.sendEmptyMessage(FUNCTIONCODE)
            }
            R.id.bt02 -> {
                if (!Tools.isNull(et_pos.text.toString()) and !Tools.isNull(et_length.text.toString()) and !Tools.isNull(et_key.text.toString())) {
                    if (et_key.text.toString().length == 17) {
                        if (et_pos.text.toString().toInt() < 16) {
                            if ((et_pos.text.toString().toInt() + et_length.text.toString().toInt()) < 17) {
                                QRCode = "5354" + modeValue + getAddr(addrValue.toInt()) + getAddr(et_pos.text.toString().replace(" ", "").toInt()) + getAddr(et_length.text.toString().replace(" ", "").toInt()) + getKEYTYPE(keyValue) + et_key.text.toString().replace(" ", "")
                                QRCode += Tools.getXor(QRCode)
                                handler.sendEmptyMessage(MODECODE)
                            } else {
                                Toast.makeText(this, "POS plus Length is No more than 16", Toast.LENGTH_LONG).show()
                            }
                        } else {
                            Toast.makeText(this, "POS is No more than 16", Toast.LENGTH_LONG).show()
                        }
                    } else {
                        Toast.makeText(this, "KEY length is error", Toast.LENGTH_LONG).show()
                    }
                } else {
                    Toast.makeText(this, "POS,LENGTH or KEY can not be empty", Toast.LENGTH_LONG).show()
                }
            }
        }
    }

    fun getAddr(add: Int): String {
        var addr = ""
        if (add > 9) {
            addr = String.format("%X", add)
            if (addr.length != 2) {
                addr = "0" + addr
            }
        } else {
            addr = "0" + add
        }
        return addr
    }

    fun getKEYTYPE(key: String): String {
        var temp = ""
        if (key.equals("KEYA")) {
            temp = "60"
        } else {
            temp = "61"
        }
        return temp
    }


    private fun setPositiveButton(
            builder: AlertDialog.Builder): AlertDialog.Builder {
        // 调用setPositiveButton方法添加“确定”按钮
        return builder.setPositiveButton("确定") { dialog, which ->
            //     show.setText("单击了【确定】按钮！")
        }
    }

    private fun setNegativeButton(
            builder: AlertDialog.Builder): AlertDialog.Builder {
        // 调用setNegativeButton方法添加“取消”按钮
        return builder.setNegativeButton("取消") { dialog, which ->
            // show.setText("单击了【取消】按钮！")
        }
    }

    /* */
    /**
     * get xor(parity bit)
     *//*
    private fun getXor(requestComm: String): String {
        val buff = java.util.ArrayList<String>()
        var i = 0
        while (i < requestComm.length) {
            buff.add(requestComm.substring(i, i + 2))
            i = i + 2
        }
        var r = 0
        for (b in buff) {
            //把16进制的转换为10进制的数进行异或操作
            r = r xor Integer.parseInt(b, 16)
        }
        //得到异或的数之后在转换成16进制的
        val hex = Integer.toHexString(r and 0xFF)
        return if (hex.length == 1) {
            "0$hex"
        } else hex
    }*/

    override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
        when (p0!!.id) {
            R.id.spinner_function_list -> {
                if (p2 == 15) {
                    isSettingScannerGun = true
                } else {
                    isSettingScannerGun = false
                    functionValue = functionValueArray[p2]
                }
            }
            R.id.spinner_working_mode -> {
                modeValue = modeValueArray[p2]
            }
            R.id.spinner_memory_addr -> {
                addrValue = addrArray[p2]
            }
            R.id.spinner_key -> {
                keyValue = keyArray[p2]
            }
        }
    }

    override fun onNothingSelected(p0: AdapterView<*>?) {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }
}
