package com.seatel.mobilehall.ui.profile.activity

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import at.nineyards.anyline.AnylineDebugListener
import at.nineyards.anyline.camera.CameraController
import at.nineyards.anyline.camera.CameraOpenListener
import at.nineyards.anyline.core.RunFailure
import at.nineyards.anyline.models.AnylineImage
import com.android.volley.VolleyError
import com.google.gson.Gson
import com.seatel.mobilehall.R
import com.seatel.mobilehall.data.network.SeatelRequest
import com.seatel.mobilehall.ui.profile.interactor.ScanMRZInteractor
import com.seatel.mobilehall.ui.profile.model.ScanModuleEnum
import com.seatel.mobilehall.ui.profile.presenter.ScanMRZPresenter
import com.seatel.mobilehall.util.Constant
import com.seatel.mobilehall.util.ScanMRZSharePref
import com.seatel.mobilehall.util.SeatelAlertDialog
import com.seatel.mobilehall.util.SeatelUtils
import io.anyline.plugin.id.*
import io.anyline.view.ScanView
import kotlinx.android.synthetic.main.activity_scan_mrz.*
import org.json.JSONObject

open class ScanMRZActivity : ScanActivity(), CameraOpenListener, AnylineDebugListener,
    ScanMRZInteractor.View {
    private val TAG: String = ScanMRZActivity::class.java.simpleName
    private val notificationToast: Toast? = null
    private lateinit var mScanMrz: ScanView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_scan_mrz)
        mScanMrz = findViewById(R.id.mrz_view)
        mScanMrz.setScanConfig("mrz_view_config.json")
        if (ScanMRZSharePref.getConstant(this).scanMrzKey.isEmpty()) {
            showProgress()
            ScanMRZPresenter(this).onRequestMRZKey()
        } else {
            init(ScanMRZSharePref.getConstant(this).scanMrzKey)
            Log.d(
                "---anyLineKey",
                "onGetMRZKeySucceed: ${ScanMRZSharePref.getConstant(this).scanMrzKey}"
            )
        }

        if (intent.getBooleanExtra("isRegisterType", false)) {
            text_view_input_manually.visibility = View.VISIBLE
            text_view_or.visibility = View.VISIBLE

            text_view_input_manually.setOnClickListener {
                setResult(Activity.RESULT_FIRST_USER)
                onBackPressed()
            }
        }
        button_close.setOnClickListener {
            onBackPressed()
        }


    }

    override fun isDisplayToolbar(): Boolean {
        return false
    }

    private fun init(key: String) {
        val mrzConfig = MrzConfig()

        val fieldScanOption = MrzFieldScanOptions()
        fieldScanOption.vizDateOfIssue = IDFieldScanOptions.FieldScanOption.DEFAULT
        fieldScanOption.vizAddress = IDFieldScanOptions.FieldScanOption.DEFAULT
        fieldScanOption.vizGivenNames = IDFieldScanOptions.FieldScanOption.DEFAULT
        fieldScanOption.vizSurname = IDFieldScanOptions.FieldScanOption.DEFAULT
        fieldScanOption.vizDateOfBirth = IDFieldScanOptions.FieldScanOption.DEFAULT
        fieldScanOption.vizDateOfExpiry = IDFieldScanOptions.FieldScanOption.DEFAULT


        mrzConfig.setIdFieldScanOptions(fieldScanOption)
        mrzConfig.isStrictMode = false
        mrzConfig.enableFaceDetection(true)


        //init the scan view
        //init the scan view
        val scanViewPlugin = IdScanViewPlugin(
            applicationContext, key, mScanMrz.scanViewPluginConfig,
            mrzConfig
        )
        mScanMrz.scanViewPlugin = scanViewPlugin
        scanViewPlugin.addScanResultListener { idScanResult ->
            val identification =
                idScanResult.result as MrzIdentification
            val currentBitmap = identification.faceImage
            val newImage = AnylineImage(currentBitmap)
            //set the path of the mrz Image
            val path =
                setupImagePath(idScanResult.cutoutImage)
            val facePath = setupImagePath(newImage)
            /* startScanResultIntent(
            resources.getString(R.string.title_mrz),
            getIdentificationResult(identification),
            path,
            facePath
            )*/
            //Intent
            val data = identification.toJSONObject() as JSONObject
            Log.d(TAG, "init: " + Gson().toJson(data))
            val intent = Intent()
            intent.putExtra(Constant.MRZ_FIRST_NAME, data.optString("surname"))
            intent.putExtra(Constant.MRZ_LAST_NAME, data.optString("givenNames"))
            intent.putExtra(Constant.MRZ_ID, data.optString("documentNumber"))
            intent.putExtra(Constant.MRZ_DOB, data.optString("dateOfBirthObject"))
            intent.putExtra(Constant.MRZ_GENDER, data.optString("sex"))
            intent.putExtra(Constant.MRZ_DOCUMENT_TYPE, data.optString("documentType"))
            intent.putExtra("imagePath", path)
            setResult(Activity.RESULT_OK, intent)
            onBackPressed()
            //     val data = identification.toJSONObject() as JSONObject
            //   Log.d("---documentType", data.optString("documentType"))

            setupScanProcessView(this, idScanResult, scanModule)
        }
    }


    override fun onResume() {
        super.onResume()
        mScanMrz = findViewById(R.id.mrz_view)
        mScanMrz.start()
        if (!ScanMRZSharePref.getConstant(this).scanMrzKey.isEmpty())
            init(ScanMRZSharePref.getConstant(this).scanMrzKey)


    }

    override fun onPause() {
        super.onPause()
        mScanMrz = findViewById(R.id.mrz_view)
        mScanMrz.stop()
        mScanMrz.releaseCameraInBackground()
    }

    override fun getScanView(): ScanView? {
        return null
    }

    override fun getScanModule(): ScanModuleEnum.ScanModule {
        return ScanModuleEnum.ScanModule.MRZ
    }

    override fun onCameraError(p0: Exception?) {
        throw RuntimeException(p0)
    }

    override fun onCameraOpened(p0: CameraController?, width: Int, height: Int) {
        //the camera is opened async and this is called when the opening is finished
        Log.d(TAG, "Camera opened successfully. Frame resolution $width x $height")
    }

    override fun onRunSkipped(runFailure: RunFailure?) {
        /* if (runFailure != null && runFailure.errorCode() == exception_error_codes.PointsOutOfCutout.swigValue()) {
             showToast(runFailure.message)
         }*/
    }


    override fun onDebug(p0: String?, p1: Any?) {

    }

    override fun onGetMRZKeyFailed(error: VolleyError) {
        hideProgress()
        SeatelAlertDialog.with(
            this,
            SeatelUtils.translatForDialog(this, SeatelRequest.getErrorMessageFrom(error))
        ).setDismiss {
            finish()
        }.show()


    }

    override fun onGetMRZKeySucceed(key: String) {
        hideProgress()
        ScanMRZSharePref.getConstant(this).scanMrzKey = key

        init(key)
    }

    companion object {
        fun launchForResult(context: Context) {
            val intent = Intent(context, ScanMRZActivity::class.java)
            (context as Activity).startActivityForResult(intent, Constant.SCAN_MRZ)

        }
    }


}