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.ui.base.activity.BaseActivity
import com.seatel.mobilehall.ui.login.model.UploadImageResponse
import com.seatel.mobilehall.util.*
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.android.synthetic.main.activity_order_payment_success.*
import kotlinx.android.synthetic.main.view_activate_buy_sim.view.*
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.*


class OrderPaymentSuccessActivity : BaseActivity() {

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

    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)) {
                activate_sim_view.displayForUpdateSimNoneSeatelUser()
            }

        button_my_order.setOnClickListener {
            MyOrderActivity.lunch(this)
            finish()
            activityExitDownAnimation()
        }

        button_return_ehub.setOnClickListener {
            EShopPhaseTwoActivity.lunch(this)
            finish()
            activityExitDownAnimation()
        }

        if (OrderingManager.getInstance().isBuySim) {
            layout_go_main.visibility = View.GONE
            activate_sim_view.visibility = View.VISIBLE
            layout_button_done.visibility = View.VISIBLE
        } else {
            layout_go_main.visibility = View.VISIBLE
            activate_sim_view.visibility = View.GONE
            layout_button_done.visibility = View.GONE
        }
        activate_sim_view.edit_text_name.setText(getProfile().custName)
        tv_order_id.text = SeatelUtils.translatForDialog(this, "Your order") + String.format(
            Locale.US,
            " #: %s",
            getOrderId()
        )
        button_done.setOnClickListener { uploadImage() }
    }

    private fun postInfo() {
        if (activate_sim_view.mOutputFileBack != null && imageBackFileName.isEmpty()) {
            return
        }
        if (activate_sim_view.mOutputFileFront != null && imageFrontFileName.isEmpty()) {
            return
        }
        if (activate_sim_view.mOutputFileUser != null && imageUserFileName.isEmpty()) {
            return
        }

        error_view.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",
                    activate_sim_view.edit_text_card_number.text.toString().trim()
                )
                profile.put(
                    "name",
                    activate_sim_view.edit_text_name.text.toString()
                ) //getProfile().custName)
                profile.put("certName", activate_sim_view.tv_id_type.text.toString())
                profile.put("gender", activate_sim_view.tv_sex.text.toString())
                profile.put("dateOfBirth", activate_sim_view.dateOfBirth)
                profile.put("frontIDPhotoUrl", imageFrontFileName)
                profile.put("backIDPhotoUrl", imageBackFileName)
                profile.put(
                    "photoUrl",
                    if (activate_sim_view.radio_button_current_info.isChecked) 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 {
            error_view.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()
            error_view.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 (activate_sim_view.mOutputFileBack != null) {
            upload(Response.Listener {
                imageBackFileName = getUploadResponseModel(it).data[0].filename
                postInfo()
            }, activate_sim_view.mOutputFileBack!!)
        }

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

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

    }

    private fun isValidData(): Boolean {
        if (TextUtils.isEmpty(activate_sim_view.tv_id_type.text.toString())) {
            SeatelAlertDialog.with(this, "Please select Document Type.").show()
            return false
        }
        if (TextUtils.isEmpty(activate_sim_view.edit_text_card_number.text.toString())) {
            SeatelAlertDialog.with(this, "Please input your ID number.").show()
            return false
        }
        if (TextUtils.isEmpty(activate_sim_view.edit_text_name.text.toString())) {
            SeatelAlertDialog.with(this, "Please input your name.").show()
            return false
        }
        if (TextUtils.isEmpty(activate_sim_view.tv_sex.text.toString())) {
            SeatelAlertDialog.with(this, "Please select your gender.").show()
            return false
        }
        if (TextUtils.isEmpty(activate_sim_view.dateOfBirth)) {
            SeatelAlertDialog.with(this, "Please select your date of birth.").show()
            return false
        }
        if (activate_sim_view.mOutputFileFront == null) {
            SeatelAlertDialog.with(this, "Please take picture ID front.").show()
            return false
        }
        if (activate_sim_view.mOutputFileBack == null) {
            SeatelAlertDialog.with(this, "Please take picture ID back.").show()
            return false
        }
        if (activate_sim_view.radio_button_new_id.isChecked && activate_sim_view.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 -> {
                    activate_sim_view.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)


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


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

                }
                Constant.SCAN_MRZ -> {
                    if (data != null)
                        activate_sim_view.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)
        }
    }
}
