package com.seatel.mobilehall.ui.invite_friend

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.Vibrator
import android.util.Log
import android.view.SurfaceHolder
import android.view.View
import android.view.animation.Animation
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.android.volley.Request
import com.google.android.gms.vision.CameraSource
import com.google.android.gms.vision.Detector
import com.google.android.gms.vision.barcode.Barcode
import com.google.android.gms.vision.barcode.BarcodeDetector
import com.google.gson.Gson
import com.seatel.mobilehall.R
import com.seatel.mobilehall.data.network.SeatelJSONObjectRequest
import com.seatel.mobilehall.data.network.SeatelSuperRequest
import com.seatel.mobilehall.ui.base.activity.BaseActivity
import com.seatel.mobilehall.ui.home.model.QrSuccessModel
import com.seatel.mobilehall.util.Constant
import com.seatel.mobilehall.util.SeatelAlertDialog
import com.seatel.mobilehall.util.customview.ErrorHandleView
import kotlinx.android.synthetic.main.activity_qr_code.*
import kotlinx.android.synthetic.main.fragment_profile.error_view
import org.json.JSONException
import org.json.JSONObject
import java.io.IOException


class InviteFriendScanQrActivity : BaseActivity() {
    private val TAG: String = "ScanQrActivity::>>>"

    private var phoneNumber: String? = null
    private val requestCodeCameraPermission = 101
    private lateinit var cameraSource: CameraSource
    private lateinit var barcodeDetector: BarcodeDetector
    private lateinit var aniSlide: Animation


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_qr_code)
        requestCamera()
        overlay.post {
            overlay.setViewFinder()
        }

    }

    private fun requestCamera() {
        if (ContextCompat.checkSelfPermission(
                this@InviteFriendScanQrActivity,
                android.Manifest.permission.CAMERA
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            askForCameraPermission()
        } else {
            setupControls()
        }

        /*aniSlide =
            AnimationUtils.loadAnimation(this@ScanQrActivity, R.anim.scanner_animation)
        barcode_line.startAnimation(aniSlide)*/
    }

    private fun askForCameraPermission() {
        ActivityCompat.requestPermissions(
            this@InviteFriendScanQrActivity,
            arrayOf(android.Manifest.permission.CAMERA),
            requestCodeCameraPermission
        )
    }

    private fun setupControls() {
        barcodeDetector =
            BarcodeDetector.Builder(this).setBarcodeFormats(Barcode.ALL_FORMATS).build()

        cameraSource = CameraSource.Builder(this, barcodeDetector)
            .setRequestedPreviewSize(1920, 1080)
            .setAutoFocusEnabled(true) //you should add this feature
            .build()

        Log.d(TAG, "+---------> setUpQRScanner <---------+")
        cameraSurfaceView.holder.addCallback(object : SurfaceHolder.Callback {
            @SuppressLint("MissingPermission")
            override fun surfaceCreated(holder: SurfaceHolder) {
                try {
                    Log.d(TAG, "+---------> surfaceCreated <---------+")
                    if (ActivityCompat.checkSelfPermission(
                            this@InviteFriendScanQrActivity,
                            Manifest.permission.CAMERA
                        ) != PackageManager.PERMISSION_GRANTED
                    ) {
                        return
                    }
                    Log.d(TAG, "+---------> start <---------+")
                    cameraSource.start(cameraSurfaceView.holder)
                } catch (e: IOException) {
                    Log.e("CAMERA SOURCE", e.message.toString())
                }
            }

            @SuppressLint("MissingPermission")
            override fun surfaceChanged(
                holder: SurfaceHolder,
                format: Int,
                width: Int,
                height: Int
            ) {
                Log.d(TAG, "+---------> surfaceChanged <---------+")
            }

            override fun surfaceDestroyed(holder: SurfaceHolder) {
                cameraSource.stop()
            }
        })


        barcodeDetector.setProcessor(object : Detector.Processor<Barcode> {
            override fun release() {
                Log.d(TAG, "+---------> release <---------+")
            }

            override fun receiveDetections(detections: Detector.Detections<Barcode>) {
                val barcodes = detections.detectedItems
                if (barcodes.size() != 0) {
                    barcodeDetector.release()
                    runOnUiThread {
                        try {
                            val vibrator =
                                applicationContext.getSystemService(VIBRATOR_SERVICE) as Vibrator
                            vibrator.vibrate(500)
                            Log.d(TAG, barcodes.valueAt(0).displayValue)
                            phoneNumber = barcodes.valueAt(0).displayValue
                            val intent = Intent()
                            intent.putExtra("resultBarcode", phoneNumber)
                            getScanData(phoneNumber.toString())
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
                    }
                }

                /*if (barcodes.size() == 1) {
                    Log.d(TAG, barcodes.valueAt(0).displayValue)
                    tv_scanned_code.post {
                        try {
                            clearScannedData()
                            phoneNumber = barcodes.valueAt(0).displayValue
                            getScanData(phoneNumber.toString())
                        } catch (ex: Exception) {
                            ex.printStackTrace()
                        }

                    }
                }*/


            }
        })
    }

    private fun getScanData(mData: String) {
        Log.d(TAG, "getScanData: is working")
        cameraSource.stop()
        error_view.setViewMode(ErrorHandleView.Mode.LOADING)
        object : SeatelJSONObjectRequest(this@InviteFriendScanQrActivity) {
            override fun getFunctionName(): String {
                return "v2/seatel/create-referal"
            }

            override fun onGetBodyRequest(): String {
                val data = JSONObject()
                try {
                    data.put("referrerNBR", "${getPhoneLogin()}")
                    data.put("refereeNBR", "$mData")
                } catch (e: JSONException) {
                    e.printStackTrace()
                }

                return data.toString()
            }

            override fun getMethod(): Int {
                return Request.Method.POST
            }

        }.setOnErrorListener {
            error_view.visibility = View.GONE
            SeatelAlertDialog.with(
                this@InviteFriendScanQrActivity,
                SeatelSuperRequest.getErrorMessageFrom(it)
            )
                .setPositiveButton("Yes") { dialog, _ ->
                    dialog.dismiss()
                    setupControls()
                    clearScannedData()
                }.show()

        }.execute {
            val response = it as JSONObject
            val data =
                Gson().fromJson(response.toString(), QrSuccessModel::class.java)
            if (!data.message.isNullOrEmpty() && data.message == "successfully") {
                InviteFriendScanSuccessActivity.launch(
                    this@InviteFriendScanQrActivity,
                    data.phoneNumber,
                    data.data,
                    data.date,
                    data.title,
                    data.subtitle
                )
                error_view.visibility = View.GONE
            }
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == requestCodeCameraPermission && grantResults.isNotEmpty()) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                setupControls()
            } else {
                Toast.makeText(applicationContext, "Permission Denied", Toast.LENGTH_SHORT).show()
            }
        }
    }


    private fun clearScannedData() {
        if (ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.CAMERA
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            return
        }
        try {
            cameraSource.start(cameraSurfaceView.holder)
        } catch (ex: Exception) {
            ex.printStackTrace()
            Toast.makeText(
                this@InviteFriendScanQrActivity,
                "Camera is not working",
                Toast.LENGTH_SHORT
            ).show()
        }


    }

    override fun onPause() {
        super.onPause()
        Log.d(TAG, "--------------> onPause: is working <----------------")
    }

    override fun onResume() {
        super.onResume()
        Log.d(TAG, "-----------> onResume: is working <----------------")

    }

    override fun getToolbarTitle(): String {
        return resources.getString(R.string.scan_qr)
    }

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

    }


}