package com.seatel.mobilehall.ui.home.activity

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.text.TextUtils
import android.view.View
import com.android.volley.Request
import com.android.volley.Response
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.databinding.ActivityOrderPaymentSuccessBinding
import com.seatel.mobilehall.ui.base.activity.BaseActivity
import com.seatel.mobilehall.ui.login.model.UploadImageResponse
import com.seatel.mobilehall.util.Constant
import com.seatel.mobilehall.util.FileUtils
import com.seatel.mobilehall.util.MultipartEntityRequest
import com.seatel.mobilehall.util.SeatelAlertDialog
import com.seatel.mobilehall.util.SeatelUtils
import com.seatel.mobilehall.util.customview.ErrorHandleView
import com.seatel.mobilehall.util.manager.OrderingManager
import id.zelory.compressor.Compressor
import id.zelory.compressor.constraint.format
import id.zelory.compressor.constraint.quality
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
import java.io.IOException
import java.util.Locale


class OrderPaymentSuccessActivity : BaseActivity<ActivityOrderPaymentSuccessBinding>() {

    var imageFrontFileName = ""
    var imageBackFileName = ""
    var imageUserFileName = ""

    override fun getViewBinding(): ActivityOrderPaymentSuccessBinding {
        return ActivityOrderPaymentSuccessBinding.inflate(layoutInflater)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //  setContentView(R.layout.activity_order_payment_success)
        activityEnterUpAnimation()

        if (intent.hasExtra("NONE_SEATEL_USER"))
            if (intent.getBooleanExtra("NONE_SEATEL_USER", false)) {
                binding.activateSimView.displayForUpdateSimNoneSeatelUser()
            }

        binding.buttonMyOrder.setOnClickListener {
            MyOrderActivity.lunch(this)
            finish()
            activityExitDownAnimation()
        }

        binding.buttonReturnEhub.setOnClickListener {
            EShopPhaseTwoActivity.lunch(this)
            finish()
            activityExitDownAnimation()
        }

        if (OrderingManager.getInstance().isBuySim) {
            binding.layoutGoMain.visibility = View.GONE
            binding.activateSimView.visibility = View.VISIBLE
            binding.layoutButtonDone.visibility = View.VISIBLE
        } else {
            binding.layoutGoMain.visibility = View.VISIBLE
            binding.activateSimView.visibility = View.GONE
            binding.layoutButtonDone.visibility = View.GONE
        }
        binding.activateSimView.setEditeTextName(getProfile().custName)
        binding.tvOrderId.text = SeatelUtils.translatForDialog(this, "Your order") + String.format(
            Locale.US,
            " #: %s",
            getOrderId()
        )
        binding.buttonDone.setOnClickListener { uploadImage() }
    }

    private fun postInfo() {

        if (binding.activateSimView.mOutputFileBack != null && imageBackFileName.isEmpty()) {
            return
        }
        if (binding.activateSimView.mOutputFileFront != null && imageFrontFileName.isEmpty()) {
            return
        }
        if (binding.activateSimView.mOutputFileUser != null && imageUserFileName.isEmpty()) {
            return
        }

        binding.errorView.setViewMode(ErrorHandleView.Mode.LOADING)
        object : SeatelJSONObjectRequest(this@OrderPaymentSuccessActivity) {

            override fun getFunctionName(): String {
                return return if (isUpdateInfo())
                    "orders"
                else "orders/" + getOrderId()
            }

            override fun onGetBodyRequest(): String {
                val info = JSONObject()
                val profile = JSONObject()
                profile.put(
                    "idCardNumber",
                    binding.activateSimView.getEditTextCardNumber()
                )
                profile.put(
                    "name", binding.activateSimView.getEditTextName()
                ) //getProfile().custName)
                profile.put("certName", binding.activateSimView.getTvIdType())
                profile.put("gender", binding.activateSimView.getTvSex())
                profile.put("dateOfBirth", binding.activateSimView.dateOfBirth)
                profile.put("frontIDPhotoUrl", imageFrontFileName)
                profile.put("backIDPhotoUrl", imageBackFileName)
                profile.put(
                    "photoUrl",
                    if (binding.activateSimView.isRadioButtonCurrentInfo()) getProfile().imageUrl else imageUserFileName
                )

                info.put("profile", profile)
                if (isUpdateInfo()) {
                    val orderId = JSONArray()
                    val data = getOrderIdList()
                    for (i in 0..(data.size - 1)) {
                        orderId.put(data[i])
                    }
                    info.put("orderIds", orderId)
                } else info.put("orderServiceStatus", "processing")
                return info.toString()
            }

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

        }.setOnErrorListener {
            binding.errorView.visibility = View.GONE
            SeatelAlertDialog.with(this, SeatelSuperRequest.getErrorMessageFrom(it)).show()
        }.execute {
            SeatelAlertDialog(
                this,
                getString(R.string.meesage_register_sim_success)
            ).setPositiveButton("Yes") { dialog, _ ->
                dialog?.dismiss()
//                super.onBackPressed()
                gotoMainScreen()
                finish()
                activityExitDownAnimation()
            }.show()
            binding.errorView.visibility = View.GONE
        }
    }

    private fun getOrderIdList(): ArrayList<Int> {
        return if (intent.hasExtra(Constant.ORDER_ID_LIST))
            intent.getIntegerArrayListExtra(Constant.ORDER_ID_LIST)!!
        else ArrayList()
    }

    private fun isUpdateInfo(): Boolean {
        return intent.getBooleanExtra(Constant.ORDER_INFO_UPDATE, false)
    }

    private fun getOrderId(): String {
        return intent.getStringExtra(Constant.ORDER_ID)!!
    }

    private fun uploadImage() {
        if (!isValidData()) {
            return
        }

        if (binding.activateSimView.mOutputFileBack != null) {
            upload(Response.Listener {
                imageBackFileName = getUploadResponseModel(it).data[0].filename
                postInfo()
            }, binding.activateSimView.mOutputFileBack!!)
        }

        if (binding.activateSimView.mOutputFileFront != null) {
            upload(Response.Listener {
                imageFrontFileName = getUploadResponseModel(it).data[0].filename
                postInfo()
            }, binding.activateSimView.mOutputFileFront!!)
        }

        if (binding.activateSimView.mOutputFileUser != null) {
            upload(Response.Listener {
                imageUserFileName = getUploadResponseModel(it).data[0].filename
                postInfo()
            }, binding.activateSimView.mOutputFileUser!!)
        }

    }

    private fun isValidData(): Boolean {
        if (TextUtils.isEmpty(binding.activateSimView.getTvIdType())) {
            SeatelAlertDialog.with(this, "Please select Document Type.").show()
            return false
        }
        if (TextUtils.isEmpty(binding.activateSimView.getEditTextCardNumber())) {
            SeatelAlertDialog.with(this, "Please input your ID number.").show()
            return false
        }
        if (TextUtils.isEmpty(binding.activateSimView.getEditTextName())) {
            SeatelAlertDialog.with(this, "Please input your name.").show()
            return false
        }
        if (TextUtils.isEmpty(binding.activateSimView.getTvSex())) {
            SeatelAlertDialog.with(this, "Please select your gender.").show()
            return false
        }
        if (TextUtils.isEmpty(binding.activateSimView.dateOfBirth)) {
            SeatelAlertDialog.with(this, "Please select your date of birth.").show()
            return false
        }
        if (binding.activateSimView.mOutputFileFront == null) {
            SeatelAlertDialog.with(this, "Please take picture ID front.").show()
            return false
        }
        if (binding.activateSimView.mOutputFileBack == null) {
            SeatelAlertDialog.with(this, "Please take picture ID back.").show()
            return false
        }
        if (binding.activateSimView.isRadioButtonCurrentInfo() && binding.activateSimView.mOutputFileUser == null) {
            SeatelAlertDialog.with(this, "Please take your photo.").show()
            return false
        }
        return true
    }

    private fun getUploadResponseModel(data: String): UploadImageResponse {
        return Gson().fromJson(data, UploadImageResponse::class.java)
    }

    private fun upload(response: Response.Listener<String>, file: File) {
        val multi = MultipartEntityRequest.with(this).setType(Constant.ANY).setFile(file)

        multi.setOnErrorListener {
            SeatelAlertDialog.with(this, "Please check your internet connection and try again!")
                .show()
        }

        multi.upLoadImage(response)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK)
            when (requestCode) {
                Constant.REQUEST_TAKE_PHOTO -> {
                    binding.activateSimView.doCrop(Constant.REQUEST_CROP_PHOTO)
                }

                Constant.REQUEST_LOAD_PHOTO -> {
                    if (data != null && data.data != null) {
                        val actualImage = FileUtils.from(this, data.data)

                        GlobalScope.launch {
                            val file =
                                Compressor.compress(this@OrderPaymentSuccessActivity, actualImage) {
                                    quality(60)
                                    format(Bitmap.CompressFormat.JPEG)


                                }
                            binding.activateSimView.mImageCaptureUri = Uri.fromFile(file)
                            binding.activateSimView.doCrop(Constant.REQUEST_CROP_PHOTO)
                        }


                    }
                }

                Constant.REQUEST_CROP_PHOTO -> {
                    val selectedImage = data?.data
                    try {
                        val bitmap =
                            MediaStore.Images.Media.getBitmap(contentResolver, selectedImage)
                        binding.activateSimView.setImageCrop(bitmap)
                    } catch (e: IOException) {
                        e.printStackTrace()
                    }

                }

                Constant.SCAN_MRZ -> {
                    if (data != null)
                        binding.activateSimView.onScanIdCardResult(data)
                }
            }
    }

    override fun onBackPressed() {
        if (OrderingManager.getInstance().isBuySim) {
            SeatelAlertDialog.with(this, "Please fill your information.").show()
        } else {
            super.onBackPressed()
            gotoMainScreen()
            finish()
            activityExitDownAnimation()
        }
    }


    override fun isDisplayToolbar(): Boolean {
        return false
    }

    companion object {
        fun launch(context: Context, orderId: String, isNoneSeatelUser: Boolean = false) {
            val intent = Intent(context, OrderPaymentSuccessActivity::class.java)
            intent.putExtra(Constant.ORDER_ID, orderId)
            intent.putExtra("NONE_SEATEL_USER", isNoneSeatelUser)
            context.startActivity(intent)
        }

        fun launchInputInfo(
            context: Context,
            orderId: String,
            isUpdateInfo: Boolean = false,
            orderList: ArrayList<Int>,
            isNoneSeatelUser: Boolean = false
        ) {
            val intent = Intent(context, OrderPaymentSuccessActivity::class.java)
            intent.putExtra(Constant.ORDER_ID, orderId)
            intent.putExtra(Constant.ORDER_INFO_UPDATE, isUpdateInfo)
            intent.putExtra("NONE_SEATEL_USER", isNoneSeatelUser)
            intent.putIntegerArrayListExtra(Constant.ORDER_ID_LIST, orderList)
            context.startActivity(intent)
        }
    }
}
