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

import android.content.Context
import android.content.Intent
import android.graphics.Typeface
import android.os.Build
import android.os.Bundle
import android.text.Html
import android.text.SpannableString
import android.text.style.StyleSpan
import android.util.Log
import android.view.View
import android.view.ViewGroup
import com.android.volley.VolleyError
import com.google.gson.Gson
import com.seatel.mobilehall.R
import com.seatel.mobilehall.data.network.SeatelSuperRequest
import com.seatel.mobilehall.ui.base.activity.BaseActivity
import com.seatel.mobilehall.ui.home.interactor.BuyDataPackFreedomInteractor
import com.seatel.mobilehall.ui.home.model.ValuePackSectionModel
import com.seatel.mobilehall.ui.home.model.ValuePackTableModel
import com.seatel.mobilehall.ui.home.presenter.BuyDataPackFreedomPresenter
import com.seatel.mobilehall.util.Constant
import com.seatel.mobilehall.util.SeatelAlertDialog
import com.seatel.mobilehall.util.SeatelUtils
import com.seatel.mobilehall.util.customview.ErrorHandleView
import kotlinx.android.synthetic.main.activity_confirm_buy_data_pack.button_ok
import kotlinx.android.synthetic.main.activity_confirm_buy_data_pack.ctv_buy_data
import kotlinx.android.synthetic.main.activity_confirm_buy_data_pack.ctv_deduct
import kotlinx.android.synthetic.main.activity_confirm_buy_data_pack.cv_data_buy
import kotlinx.android.synthetic.main.activity_confirm_buy_data_pack.cv_data_valid_value_pack
import kotlinx.android.synthetic.main.activity_confirm_buy_data_pack.error_view
import kotlinx.android.synthetic.main.activity_confirm_buy_data_pack.image_view_back
import kotlinx.android.synthetic.main.activity_confirm_buy_data_pack.tv_phone_number
import java.text.DecimalFormat

class ConfirmBuyDataPackActivity : BaseActivity(), BuyDataPackFreedomInteractor.View {

    private var isDataFreedom: Boolean = false
    private var isValuePack: Boolean = false
    private var isFortunePlan: Boolean = false
    private var isVipFortunePlan: Boolean = false
    private var isloykob: Boolean = false
    private var isTypeAddon: String = ""
    private var mDataValuePack: ValuePackTableModel? = null
    private lateinit var mBuyDataPackFreedomPresenter: BuyDataPackFreedomPresenter
    private lateinit var mBuyDataPackFreedomInteractor: BuyDataPackFreedomInteractor.View
    private var mAmountPost: Double = 0.0
    private var mDataSize = ""
    private var mAccountNumber = ""
    private var isAllowBackPressed = true
    private var mTypeBuy = ""

    //update
    private var name: String = ""
    private var type: String = ""
    private var validity: String = ""
    private var fee: String = ""
    private var data: String = ""
    private var isAddON: Boolean = false
    private var pricePlanCode: String = ""
    private var requestTime: String? = null

    //  private var valuePackSectionModel: ValuePackSectionModel? = null


    override fun onBuyDataSucceed() {
        SuccessBuyDataPackActivity.launch(this, name, data, isAddON)/* if (isValuePack || isFortunePlan || isVipFortunePlan) mDataValuePack?.let {
             when {
                 isFortunePlan -> {
                     SuccessBuyDataPackActivity.lunchFromValuePack(this, it, isFortunePlan = true)
                 }
                 isVipFortunePlan -> {
                     SuccessBuyDataPackActivity.lunchFromValuePack(this, it, isVipFortunePlan = true)
                 }
                 else -> SuccessBuyDataPackActivity.lunchFromValuePack(this, it)
             }
         }
         else SuccessBuyDataPackActivity.lunch(this, mDataSize, mAccountNumber, isDataFreedom)*/
        finish()
    }

    override fun onBuyDataFailed(error: VolleyError) {
        Log.d("---buyDataFailed", "onBuyDataFailed: $error")
        error_view.visibility = View.GONE
        SeatelAlertDialog.with(this, SeatelSuperRequest.getErrorMessageFrom(error)).show()
        button_ok.isEnabled = true
        isAllowBackPressed = true
    }

    private fun startBuyData() {
        error_view.setViewMode(ErrorHandleView.Mode.LOADING)

        if (fee.substring(1).toDouble() == 0.5 && !isValuePack && !isFortunePlan) {

            mBuyDataPackFreedomPresenter.onBuyData(
                getPhoneLogin(), type, 0.1, isAddON, pricePlanCode, requestTime!!
            )


        } else mBuyDataPackFreedomPresenter.onBuyData(
            getPhoneLogin(),
            type,
            fee.substring(1).toDouble(),
            isAddON,
            pricePlanCode,
            requestTime!!
        )
        //note: if amount 0.5 then change it to 0.1 for CRM(do it for CRM)
        /*if (mAmountPost == 0.5 && !isValuePack && !isFortunePlan) {
            mBuyDataPackFreedomPresenter.onBuyData(getPhoneLogin(), mTypeBuy, 0.1, isTypeAddon)
        } else
            mBuyDataPackFreedomPresenter.onBuyData(
                getPhoneLogin(),
                mTypeBuy,
                mAmountPost,
                isTypeAddon
            )*/
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        activityEnterFadeInAnimation()
        setContentView(R.layout.activity_confirm_buy_data_pack)

        val tsLong = System.currentTimeMillis() / 1000
        requestTime = tsLong.toString()

        mBuyDataPackFreedomInteractor = this
        mBuyDataPackFreedomPresenter =
            BuyDataPackFreedomPresenter(this, mBuyDataPackFreedomInteractor)
        getData()
        init()

    }

    private fun setupView() {
        isDataFreedom = intent.getBooleanExtra(Constant.LAUNCH_FROM, false)
        isValuePack = intent.getBooleanExtra("IS_VALUE_PACK", false)
        isFortunePlan = intent.getBooleanExtra("IS_FORTUNE_PACK", false)
        isVipFortunePlan = intent.getBooleanExtra("IS_VIP_FORTUNE_PACK", false)
        isloykob = intent.getBooleanExtra("IS_LOY_KOB", false)
        isTypeAddon = intent.getStringExtra("add-on").toString()
        mAccountNumber =
            if (intent.hasExtra(Constant.MPAY_ACCOUNT_TRANFER)) intent.getStringExtra(Constant.MPAY_ACCOUNT_TRANFER)
                .toString()
            else getPhoneLogin()
        var datePlan = 0
        if (intent.hasExtra(Constant.DURATION_PLAN_DATE_SELECT)) datePlan =
            intent.getIntExtra(Constant.DURATION_PLAN_DATE_SELECT, 0)
        val dayStr = if (datePlan > 1) SeatelUtils.translatForDialog(
            this, "Days"
        ) else SeatelUtils.translatForDialog(this, "Day")
        val dataMB: Double
        val amountMB: String
        Log.d("---isValuePack", "onCreate: $isValuePack")

        when {
            isDataFreedom -> {
                mTypeBuy = Constant.FREEDOM_INTERNET //"freedom-data"
                val amountTransfer: Long = intent.getLongExtra(Constant.MPAY_AMOUNT, 0)
                mAmountPost = amountTransfer.toDouble()
                dataMB = SeatelUtils.calcualateFreedomDataInput(amountTransfer)
                val convertSucess = SeatelUtils.displayDataFreedomDataInput(dataMB)
                val dataMBDisplay = convertSucess[0]
                mDataSize = convertSucess[0].toString()

                val str = "$dataMBDisplay${convertSucess[1]} = $"
                val wordDataBuy = SpannableString("$str$amountTransfer")
                wordDataBuy.setSpan(StyleSpan(Typeface.BOLD), 0, dataMBDisplay.length, 0)
                cv_data_buy.text = wordDataBuy

                ctv_deduct.text = "${
                    SeatelUtils.translatForDialog(
                        this, getString(R.string.we_will_deduct)
                    )
                } $$amountTransfer ${
                    SeatelUtils.translatForDialog(
                        this, getString(R.string.from_ur_balance)
                    )
                }"
            }

            isValuePack -> {
                if (intent.hasExtra("VALUE_PACK_DATA")) {
                    mTypeBuy = Constant.VALUE_PACK
                    mDataValuePack = Gson().fromJson(
                        intent.getStringExtra("VALUE_PACK_DATA"), ValuePackTableModel::class.java
                    )
                    val price = mDataValuePack?.valuePrice?.replace("$", "")
                    if (price != null) {
                        mAmountPost = price.toDouble()
                    }
                    val formatterPrice = DecimalFormat("$#0")
                    val strValidity = "${mDataValuePack?.validityDate}"
                    val amount = mDataValuePack?.priceChange?.replace("$", "")
                    val strAmount = "${formatterPrice.format(amount?.toDouble())}"

                    val formatter = DecimalFormat("$#0.00")
//                    val priceChange = mDataValuePack?.valuePrice?.replace("$","")
                    val str = "${
                        SeatelUtils.translatForDialog(
                            this, "Value Pack"
                        )
                    } <b>${mDataValuePack?.valuePrice} = $strAmount</b> "
                    val strValid = "${
                        SeatelUtils.translatForDialog(
                            this, "Valid for"
                        )
                    } <b>${strValidity.toLowerCase()}</b> "

                    cv_data_valid_value_pack.visibility = View.VISIBLE

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        cv_data_buy.text = Html.fromHtml(str, Html.FROM_HTML_MODE_COMPACT)
                        cv_data_valid_value_pack.text =
                            Html.fromHtml(strValid, Html.FROM_HTML_MODE_COMPACT)
                    } else {
                        cv_data_buy.text = Html.fromHtml(str)
                        cv_data_valid_value_pack.text = Html.fromHtml(strValid)
                    }
                    ctv_deduct.text = "${
                        SeatelUtils.translatForDialog(
                            this, getString(R.string.we_will_deduct)
                        )
                    } ${formatter.format(mAmountPost)} ${
                        SeatelUtils.translatForDialog(
                            this, getString(R.string.from_ur_balance)
                        )
                    }"
                }
            }

            isFortunePlan -> {
                if (intent.hasExtra("VALUE_PACK_DATA")) {
                    ctv_buy_data.text = "Buy Fortune Pack"
                    mTypeBuy = Constant.FORTUNE_PACK
                    mDataValuePack = Gson().fromJson(
                        intent.getStringExtra("VALUE_PACK_DATA"), ValuePackTableModel::class.java
                    )
                    val price = mDataValuePack?.valuePrice?.replace("$", "")
                    if (price != null) {
                        mAmountPost = price.toDouble()
                    }
                    //val formatterPrice = DecimalFormat("$#0")
                    val strValidity = "${mDataValuePack?.validityDate}"
                    //val amount = mDataValuePack?.priceChange
                    val strAmount = mDataValuePack?.priceChange

                    val formatter = DecimalFormat("$#0.00")
//                    val priceChange = mDataValuePack?.valuePrice?.replace("$","")
                    val str = "${
                        SeatelUtils.translatForDialog(
                            this, "Fortune Pack"
                        )
                    } <b>${mDataValuePack?.valuePrice} = $strAmount</b> "
                    val strValid = "${
                        SeatelUtils.translatForDialog(
                            this, "Valid for"
                        )
                    } <b>${strValidity.toLowerCase()}</b> "

                    cv_data_valid_value_pack.visibility = View.VISIBLE

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        cv_data_buy.text = Html.fromHtml(str, Html.FROM_HTML_MODE_COMPACT)
                        cv_data_valid_value_pack.text =
                            Html.fromHtml(strValid, Html.FROM_HTML_MODE_COMPACT)
                    } else {
                        cv_data_buy.text = Html.fromHtml(str)
                        cv_data_valid_value_pack.text = Html.fromHtml(strValid)
                    }
                    ctv_deduct.text = "${
                        SeatelUtils.translatForDialog(
                            this, getString(R.string.we_will_deduct)
                        )
                    } ${formatter.format(mAmountPost)} ${
                        SeatelUtils.translatForDialog(
                            this, getString(R.string.from_ur_balance)
                        )
                    }"
                }
            }

            isVipFortunePlan -> {
                if (intent.hasExtra("VALUE_PACK_DATA")) {
                    ctv_buy_data.text = "Buy VIP Fortune Pack"
                    mTypeBuy = Constant.VIP_FORTUNE_PACK
                    mDataValuePack = Gson().fromJson(
                        intent.getStringExtra("VALUE_PACK_DATA"), ValuePackTableModel::class.java
                    )
                    val price = mDataValuePack?.valuePrice?.replace("$", "")
                    if (price != null) {
                        mAmountPost = price.toDouble()
                    }
                    //val formatterPrice = DecimalFormat("$#0")
                    val strValidity = "${mDataValuePack?.validityDate}"
                    //val amount = mDataValuePack?.priceChange
                    val strAmount = mDataValuePack?.priceChange

                    val formatter = DecimalFormat("$#0.00")
//                    val priceChange = mDataValuePack?.valuePrice?.replace("$","")
                    val str = "${
                        SeatelUtils.translatForDialog(
                            this, "VIP Fortune Pack"
                        )
                    } <b>${mDataValuePack?.valuePrice} = $strAmount</b> "
                    val strValid = "${
                        SeatelUtils.translatForDialog(
                            this, "Valid for"
                        )
                    } <b>${strValidity.toLowerCase()}</b> "

                    cv_data_valid_value_pack.visibility = View.VISIBLE

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        cv_data_buy.text = Html.fromHtml(str, Html.FROM_HTML_MODE_COMPACT)
                        cv_data_valid_value_pack.text =
                            Html.fromHtml(strValid, Html.FROM_HTML_MODE_COMPACT)
                    } else {
                        cv_data_buy.text = Html.fromHtml(str)
                        cv_data_valid_value_pack.text = Html.fromHtml(strValid)
                    }
                    ctv_deduct.text = "${
                        SeatelUtils.translatForDialog(
                            this, getString(R.string.we_will_deduct)
                        )
                    } ${formatter.format(mAmountPost)} ${
                        SeatelUtils.translatForDialog(
                            this, getString(R.string.from_ur_balance)
                        )
                    }"
                }
            }

            isloykob -> {
                if (intent.hasExtra("VALUE_PACK_DATA")) {
                    ctv_buy_data.text = Constant.IS_LOY_KOB
                    mTypeBuy = Constant.IS_LOY_KOB
                    mDataValuePack = Gson().fromJson(
                        intent.getStringExtra("VALUE_PACK_DATA"), ValuePackTableModel::class.java
                    )
                    val price = mDataValuePack?.valuePrice?.replace("$", "")
                    if (price != null) {
                        mAmountPost = price.toDouble()
                    }
                    //val formatterPrice = DecimalFormat("$#0")
                    val strValidity = "${mDataValuePack?.validityDate}"
                    //val amount = mDataValuePack?.priceChange
                    val strAmount = mDataValuePack?.priceChange

                    val formatter = DecimalFormat("$#0.00")
//                    val priceChange = mDataValuePack?.valuePrice?.replace("$","")
                    val str = "${
                        SeatelUtils.translatForDialog(
                            this, "VIP Fortune Pack"
                        )
                    } <b>${mDataValuePack?.valuePrice} = $strAmount</b> "
                    val strValid = "${
                        SeatelUtils.translatForDialog(
                            this, "Valid for"
                        )
                    } <b>${strValidity.toLowerCase()}</b> "

                    cv_data_valid_value_pack.visibility = View.VISIBLE

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        cv_data_buy.text = Html.fromHtml(str, Html.FROM_HTML_MODE_COMPACT)
                        cv_data_valid_value_pack.text =
                            Html.fromHtml(strValid, Html.FROM_HTML_MODE_COMPACT)
                    } else {
                        cv_data_buy.text = Html.fromHtml(str)
                        cv_data_valid_value_pack.text = Html.fromHtml(strValid)
                    }
                    ctv_deduct.text = "${
                        SeatelUtils.translatForDialog(
                            this, getString(R.string.we_will_deduct)
                        )
                    } ${formatter.format(mAmountPost)} ${
                        SeatelUtils.translatForDialog(
                            this, getString(R.string.from_ur_balance)
                        )
                    }"
                }
            }

            else -> {
                mTypeBuy = Constant.INTERNET_PACK //"datapack"
                val price = intent.getStringExtra(Constant.PRICE_VALUE)
                if (price!!.isNotEmpty()) mAmountPost = price.substring(1).toDouble()
                amountMB = intent.getStringExtra(Constant.MPAY_AMOUNT).toString()
                mDataSize = amountMB

//                cv_data_buy.text = "$datePlan$dayStr (\$$price = $amountMB)"

                val str = "<font size=5>$datePlan$dayStr </font>  <b>( ${
                    SeatelUtils.formatDecimalNumber(
                        mAmountPost, "$#.##"
                    )
                } = $amountMB )</b> "
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    cv_data_buy.text = Html.fromHtml(str, Html.FROM_HTML_MODE_COMPACT)
                } else cv_data_buy.text = Html.fromHtml(str)

                ctv_deduct.text = "${
                    SeatelUtils.translatForDialog(
                        this, getString(R.string.we_will_deduct)
                    )
                } $price ${
                    SeatelUtils.translatForDialog(
                        this, getString(R.string.from_ur_balance)
                    )
                }"
            }
        }
        tv_phone_number.text = SeatelUtils.phoneNumberFormat(mAccountNumber)
        button_ok.setOnClickListener {
            startBuyData()
            button_ok.isEnabled = false
            isAllowBackPressed = false

        }

        if (isDataFreedom) {
            ctv_buy_data.text = getString(R.string.buy_freedom_internet)
        } else if (isValuePack || isFortunePlan) ctv_buy_data.text = "Activate"

        image_view_back.setOnClickListener {
            onBackPressed()
        }
    }

    private fun getData() {
        name = intent.getStringExtra("NAME").toString()
        type = intent.getStringExtra("TYPE").toString()
        validity = intent.getStringExtra("VALIDITY").toString()
        fee = intent.getStringExtra("FEE").toString()
        data = intent.getStringExtra("DATA").toString()
        isAddON = intent.getBooleanExtra("ADDON", false)
        pricePlanCode = intent.getStringExtra("PRICEPLANCODE").toString()
    }

    private fun init() {
        if (isAddON) ctv_buy_data.text = SeatelUtils.translatForDialog(this, "Buy $name Add On")
        else ctv_buy_data.text = SeatelUtils.translatForDialog(this, "Buy $name")
        cv_data_buy.text = SeatelUtils.translatForDialog(this, "$fee")
        tv_phone_number.text = getPhoneLogin()

        //    valuePackSectionModel = intent.getSerializableExtra("valuePackSectionModel") as ValuePackSectionModel
        //  ctv_buy_data.text = SeatelUtils.translatForDialog(this,"Buy ${valuePackSectionModel!!.name}")
        //  cv_data_buy.text = SeatelUtils.translatForDialog(this, "${valuePackSectionModel!!.valuePackSecTwoModel.table[0].valuePrice}")
        //  Log.d("TAG::>>>", "init: $valuePackSectionModel")

        ctv_deduct.text = "${
            SeatelUtils.translatForDialog(
                this, getString(R.string.we_will_deduct)
            )
        } $fee ${
            SeatelUtils.translatForDialog(
                this, getString(R.string.from_ur_balance)
            )
        }"
        button_ok.setOnClickListener {
            startBuyData()
            button_ok.isEnabled = false
            isAllowBackPressed = false

        }

        image_view_back.setOnClickListener {
            onBackPressed()
        }
    }

    private fun resetButtonOkMargin() {
        val paramLayout = button_ok.layoutParams as ViewGroup.MarginLayoutParams
        paramLayout.bottomMargin = 40
        button_ok.layoutParams = paramLayout
    }


    override fun onBackPressed() {
        if (isAllowBackPressed) {
            super.onBackPressed()
            super.activityExitFadeOutAnimation()
        }
    }

    companion object {
        fun lunchFromFreedom(context: Context, amount: Long, account: String, freedom: Boolean) {
            val intent = Intent(context, ConfirmBuyDataPackActivity::class.java)
            intent.putExtra(Constant.MPAY_AMOUNT, amount)
            intent.putExtra(Constant.MPAY_ACCOUNT_TRANFER, account)
            intent.putExtra(Constant.LAUNCH_FROM, freedom)
            context.startActivity(intent)
        }

        fun launchData(context: Context, valuePackSectionModel: ValuePackSectionModel) {
            val intent = Intent(context, ConfirmBuyDataPackActivity::class.java)
            intent.putExtra("valuePackSectionModel", valuePackSectionModel)
            context.startActivity(intent)
        }

        fun launch(
            context: Context,
            name: String,
            type: String,
            validity: String,
            fee: String,
            data: String,
            pricePlanCode: String,
            isAddOn: Boolean
        ) {
            val intent = Intent(context, ConfirmBuyDataPackActivity::class.java)
            intent.putExtra("NAME", name)
            intent.putExtra("TYPE", type)
            intent.putExtra("VALIDITY", validity)
            intent.putExtra("FEE", fee)
            intent.putExtra("DATA", data)
            intent.putExtra("ADDON", isAddOn)
            intent.putExtra("PRICEPLANCODE", pricePlanCode)
            context.startActivity(intent)

        }


        fun lunchFromDataPack(
            context: Context,
            amountMB: String,
            pricetMB: String,
            account: String,
            dayPlan: Int,
            freedom: Boolean,
            type: String
        ) {
            val intent = Intent(context, ConfirmBuyDataPackActivity::class.java)
            intent.putExtra(Constant.MPAY_AMOUNT, amountMB)
            intent.putExtra(Constant.PRICE_VALUE, pricetMB)
            intent.putExtra(Constant.MPAY_ACCOUNT_TRANFER, account)
            intent.putExtra(Constant.DURATION_PLAN_DATE_SELECT, dayPlan)
            intent.putExtra(Constant.LAUNCH_FROM, freedom)
            intent.putExtra("add-on", type)
            context.startActivity(intent)
        }


        fun lunchFromValuePack(
            context: Context,
            dataValuePack: ValuePackTableModel,
            type: String,
            isFortunePlan: Boolean = false,
            isVipFortunePlan: Boolean = false,
            isloykob: Boolean = false
        ) {
            val intent = Intent(context, ConfirmBuyDataPackActivity::class.java)
            when {
                isFortunePlan -> {
                    intent.putExtra("IS_FORTUNE_PACK", true)
                }

                isVipFortunePlan -> {
                    intent.putExtra("IS_VIP_FORTUNE_PACK", true)
                }

                isloykob -> {
                    intent.putExtra("IS_LOY_KOB", true)
                }

                else -> {
                    intent.putExtra("IS_VALUE_PACK", true)
                }
            }
            intent.putExtra("VALUE_PACK_DATA", Gson().toJson(dataValuePack))
            intent.putExtra("add-on", type)
            context.startActivity(intent)

        }
    }

    override fun isDisplayBackgroundBlur(): Boolean {
        return true
    }

    override fun isDisplayToolbar(): Boolean {
        return false
    }
}
