package com.mytatvarnsdk.activity

import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.os.Bundle
import android.os.Parcelable
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import cgmblelib.database.entity.PocDevice
import cgmblelib.qr.QRInformation
import cgmblelib.utils.SharedPreferencesLibraryUtil
import com.myc.library_zxing.QRFragment
import com.myc.library_zxing.view.OnFragmentListener
import com.mytatvarnsdk.R
import ist.com.sdk.AlgorithmTools
import ist.com.sdk.KRDecodeData

class QRActivity : AppCompatActivity(), View.OnClickListener {
    private var mQRFragment: QRFragment? = null
    private var mPocDevice: PocDevice? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_qr)
        findViewById<View?>(R.id.btnLeft).setOnClickListener(this)
        mPocDevice = intent.getParcelableExtra("device")
        if (mPocDevice == null) {
            finish()
        }
    }

    override fun onResume() {
        super.onResume()
        mQRFragment = QRFragment.newInstance(object : OnFragmentListener {
            override fun onPermissionRequestFail(isForever: Boolean) {
            }

            override fun onCameraOpenError(e: Exception?) {
            }

            override fun onScanResult(messages: String?, bitmap: Bitmap?) {
                Log.d("QR Info ==> ", "onScanResult: $messages")
                mQRFragment!!.restartPreviewAfterDelay(0)
            }

            override fun onScanResultFromCT2(messages: String?, bitmap: Bitmap?) {
                Log.d("QR Info ==> ", "onScanResultFromCT2: $messages")

            }

            override fun onScanResultFromCT3(messages: String, bitmap: Bitmap?) {
                decodeMessageCt3(messages)
            }

            override fun onScanResultFromCT5(messages: String?, bitmap: Bitmap?) {
            }
        })
        supportFragmentManager.beginTransaction()
            .add(R.id.container, mQRFragment!!)
            .commit()
    }


    /**
     * 进行数据解析
     *
     * @param message 需要解析的信息
     */
    private fun decodeMessageCt3(message: String) {
        Log.d("QR Info ==> ", "decodeMessageCt3: $message")

        val decodeData: KRDecodeData = AlgorithmTools.getInstance().decodeCT(message.toCharArray())

        Log.d("QR Info ==> ", "decodeData: $decodeData")

        showMessage(message, decodeData.k, decodeData.r, message)
    }

    fun showMessage(message: String?, k: Float, r: Float, sensorInfo: String?) {
        try {

            val prefsHelper = SharedPreferencesLibraryUtil(this)
            prefsHelper.setQRInformation(mPocDevice?.name, message, k, r, sensorInfo)
            val qrInformation: QRInformation? = prefsHelper.qrInformation

            Log.d("qrInformation==> ", "mPocDevice:  ${mPocDevice.toString()}")
            if (qrInformation != null && qrInformation.isEffective(mPocDevice?.name, r, k)) {
                Log.d("qrInformation==> ", "qrInformation:  $qrInformation")
                setResult(RESULT_OK, Intent().putExtra("device", mPocDevice as Parcelable))
                finish()
            } else {
                Toast.makeText(
                    this@QRActivity,
                    getString(R.string.verification_fail),
                    Toast.LENGTH_SHORT
                )
                    .show()
                mQRFragment!!.restartPreviewAfterDelay(0)
            }
        } catch (e: Exception) {
            e.printStackTrace()
            finish()
        }
    }

    override fun onClick(v: View) {
        if (v.id == R.id.btnLeft) {
            finish()
        }
    }

    companion object {
        fun startQR(activity: Activity, device: PocDevice?) {
            val intent = Intent(activity, QRActivity::class.java)
            intent.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP
            intent.putExtra("device", device as Parcelable)
            activity.startActivityForResult(intent, 115)
        }
    }
}
