package com.seatel.mobilehall.ui.login.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.util.Log
import android.view.View
import androidx.lifecycle.lifecycleScope
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.theartofdev.edmodo.cropper.CropImage
import com.theartofdev.edmodo.cropper.CropImageView
import id.zelory.compressor.Compressor
import id.zelory.compressor.constraint.format
import id.zelory.compressor.constraint.quality
import id.zelory.compressor.constraint.resolution
import kotlinx.android.synthetic.main.activity_updated_sim_profile.*
import kotlinx.android.synthetic.main.view_activate_buy_sim.view.*
import kotlinx.coroutines.launch
import org.json.JSONObject
import java.io.File

class UpdatedSimProfileActivity : BaseActivity() {

    private var imageFrontFileName = ""
    private var imageBackFileName = ""
    private var imageUserFileName = ""
    private var phoneNumber = ""
    private var isPostingRequest = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_updated_sim_profile)
        activityEnterRightAnimation()
        if (intent.hasExtra(Constant.PHONE_NUMBER))
            phoneNumber = intent.getStringExtra(Constant.PHONE_NUMBER).toString()
        ctv_phone_number_header.text = SeatelUtils.phoneNumberFormat(phoneNumber)
        activate_sim_view.displayForUpdateSimProfile()
        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
        if (isPostingRequest)
            return
        isPostingRequest = true

        error_view.setViewMode(ErrorHandleView.Mode.LOADING)
        object : SeatelJSONObjectRequest(this@UpdatedSimProfileActivity) {


            override fun getFunctionName(): String {
                return "seatel/$phoneNumber/modify"
            }

            override fun onGetBodyRequest(): String {
                val profile = JSONObject()
                profile.put("certId", activate_sim_view.getIdCertType())
                profile.put(
                    "certNum",
                    activate_sim_view.edit_text_card_number.text.toString().trim()
                )
                profile.put("name", activate_sim_view.edit_text_name.text.toString())
                profile.put("certName", activate_sim_view.getCertificationNamePost())
                profile.put("gender", activate_sim_view.getGenderKeyPost())
                profile.put("frontIdImageUrl", imageFrontFileName)
                profile.put("backIdImageUrl", imageBackFileName)
                profile.put("photoUrl", imageUserFileName)

                return profile.toString()
            }

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


        }.setOnErrorListener {
            isPostingRequest = false
            error_view.visibility = View.GONE
            SeatelAlertDialog.with(this, SeatelSuperRequest.getErrorMessageFrom(it)).show()
        }.execute {
            SeatelAlertDialog(
                this,
                getString(R.string.meesage_modify_profile_sim_success)
            ).setPositiveButton("Yes") { dialog, _ ->
                dialog?.dismiss()
                gotoMainScreen()
                finish()
                activityExitDownAnimation()
            }.show()
            error_view.visibility = View.GONE
            isPostingRequest = false
        }
    }

    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().trim()
            ) || TextUtils.isEmpty(activate_sim_view.getCertificationNamePost())
        ) {
            SeatelAlertDialog.with(this, "Please select Document Type.").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.edit_text_card_number.text.toString())) {
            SeatelAlertDialog.with(this, "Please input your ID number.").show()
            return false
        }

        if (TextUtils.isEmpty(activate_sim_view.tv_sex.text.toString())) {
            SeatelAlertDialog.with(this, "Please select your gender.").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.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 {
            if (it.networkResponse.statusCode == 413) {
                SeatelAlertDialog.with(this, "Request Entity Too Large")
                    .show()
            }
            /*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 -> {
                    setCrop()
                    //  activate_sim_view.doCrop(Constant.RequestCode.REQUEST_CROP_PHOTO)
                }
                Constant.REQUEST_LOAD_PHOTO -> {
                    if (data != null && data.data != null) {
                        val actualImage = FileUtils.from(this, data.data)
                        activate_sim_view.mImageCaptureUri = Uri.fromFile(actualImage)
                        setCrop()
                     /*   GlobalScope.launch {
                            val file =
                                Compressor.compress(this@UpdatedSimProfileActivity, actualImage) {
                                    resolution(640, 480)
                                    quality(90)
                                    format(Bitmap.CompressFormat.WEBP)

                                }

                        }*/

                        //   activate_sim_view.doCrop(Constant.RequestCode.REQUEST_CROP_PHOTO)

                    }

                }

                CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE -> {
                    val result = CropImage.getActivityResult(data)
                    if (resultCode == Activity.RESULT_OK) {
                        result.uri?.let {
                            val actualImage = FileUtils.from(this, it)
                            lifecycleScope.launch {
                                val mOutputFile =
                                    Compressor.compress(
                                        this@UpdatedSimProfileActivity,
                                        actualImage
                                    ) {
                                        resolution(640, 480)
                                        quality(90)
                                        format(Bitmap.CompressFormat.WEBP)

                                    }

                                when (activate_sim_view.imageType) {
                                    "front" -> activate_sim_view.mOutputFileFront = mOutputFile
                                    "back" -> activate_sim_view.mOutputFileBack = mOutputFile
                                    else -> activate_sim_view.mOutputFileUser = mOutputFile
                                }
                                val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, it)
                                activate_sim_view.setImageCrop(bitmap)

                            }
                        }

                    }

                }

               /* 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 -> {
                    activate_sim_view.onScanIdCardResult(data!!)
                }
            }
    }

    private fun setCrop() {
        CropImage.activity(activate_sim_view.mImageCaptureUri)
            .setGuidelines(CropImageView.Guidelines.ON)
            .start(this)
    }

    override fun onBackPressed() {
        super.onBackPressed()
        super.activityExitLeftAnimation()
    }

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

    companion object {
        fun launch(context: Context, phoneNumber: String) {
            val intent = Intent(context, UpdatedSimProfileActivity::class.java)
            intent.putExtra(Constant.PHONE_NUMBER, phoneNumber)
            context.startActivity(intent)
        }
    }

}
