package com.seatel.mobilehall.util.request

import android.content.Context
import android.text.TextUtils
import android.util.Log
import androidx.core.content.ContentProviderCompat.requireContext
import com.android.volley.VolleyError
import com.seatel.mobilehall.data.prefs.SeatelSharePreferences
import com.seatel.mobilehall.ui.home.model.MainDataModel
import com.seatel.mobilehall.ui.login.model.PromotionHomeModel
import com.seatel.mobilehall.util.Constant
import com.seatel.mobilehall.util.ScanMRZSharePref
import com.google.gson.Gson
import com.seatel.mobilehall.data.network.SeatelJSONObjectRequest
import com.seatel.mobilehall.ui.login.model.ContactService
import org.json.JSONObject
import java.util.*
import kotlin.collections.ArrayList


class GetMainData(
    context: Context?,
    val phone: String,
    val mToken: String,
    val successRespond: (sucess: Boolean) -> Unit
) : SeatelJSONObjectRequest(context) {

    override fun getFunctionName(): String {
        return Constant.MAIN_SCREEN_DATA + "$phone" + "&token=$mToken"
    }

    override fun onResponse(response: JSONObject?) {
        super.onResponse(response)
        //Save Data Main Screen
        val model = MainDataModel()
        if (response!!.has("type")) {
            val typeNone = response.optString("type")
            SeatelSharePreferences.getInstance(context)?.setIsPostPaid(
                TextUtils.equals(typeNone.lowercase(Locale.getDefault()), "postpaid")
            )
        }
        model.setTextGetMore(response.optString("mainButtonText", ""))
        model.setCustName(response.optString("custName", ""))
        model.setPlanName(response.optString("subsPlanName", ""))
        model.setPlanCode(response.optString("subsPlanCode", ""))
        model.setPhoneNumber(response.optString("mSISDN", ""))
        model.setBalance(response.optDouble("balance", 0.0))
        model.setExpDate(response.optString("expDate", ""))
        model.setValueExpDate(response.optString("valueExpDate", ""))
        model.setDataExpDate(response.optString("dataExpDate", ""))
        model.setStatus(response.optString("status", ""))
        model.setTypeAccount(response.optString("type", ""))
        model.setRemainingData(response.optDouble("remainingData", 0.0))
        model.setTotalData(response.optDouble("totalData", 0.0))
        model.setRemainingValue(response.optDouble("remainingValue", 0.0))
        model.setTotalValue(response.optDouble("totalValue", 0.0))
        model.setSimPriceDefault(response.optDouble("cardPrice", 0.5))
        model.setShipmentInsuranceRate(response.optDouble("shipmentInsuranceRate", 0.0))
        model.setIsUseValue(response.optBoolean("useValue", false))
        model.setSnowFall(response.optBoolean("snowfall", false))
        model.setFallEffectType(response.optString("fallEffectType", ""))
        model.setForceUpdate(response.optBoolean("forceUpdate", false))
        model.setIsNewUpdateAvailable(response.optBoolean("isNewUpdateAvailable", false))
        model.setUnlimitedInternet(response.optBoolean("useGaugeText", false))
        model.setTextUnlimted(response.optString("mainGaugeText", ""))
        model.setHasInstallmentPlan(response.optBoolean("hasInstalmentPlan", false))
        model.setEventGame(response.optBoolean("eventGame", false))
        model.setBannerBuySim(response.optString("bannerBuySim", ""))
        model.setBannerBuyTopup(response.optString("bannerBuyTopup", ""))
        model.setRoamingActivation(response.optBoolean("roamingActivation", false))
        model.setSpecialSimcard(response.optBoolean("specialSimcard",false))

        if (response.has("profilePicture")) model.setProfilePicture(response.optString("profilePicture"))
        if (response.has("orderIds")) {
            val dataId = response.optJSONArray("orderIds")
            val idList: ArrayList<Int> = ArrayList()
            for (i in 0..(dataId.length() - 1)) {
                idList.add(dataId.optInt(i))
            }
            model.setOrderIdUnSuccess(idList)
        }
        if (response.has("promotions")) {
            val dataPromo = response.optJSONArray("promotions")
            val promoList: ArrayList<PromotionHomeModel> = ArrayList()
            for (i in 0..(dataPromo.length() - 1)) {
                promoList.add(
                    PromotionHomeModel(
                        dataPromo.optJSONObject(i).optString("_id"),
                        dataPromo.optJSONObject(i).optString("name"),
                        dataPromo.optJSONObject(i).optString("code")
                    )
                )
            }
            model.setPromotions(promoList)
        }

        val contactService = response.optJSONArray("contactService")
        val mContactService: ArrayList<ContactService> = ArrayList()
        for (i in 0 until contactService.length()) {
            mContactService.add(
                ContactService(
                    contactService.optJSONObject(i).optString("type"),
                    contactService.optJSONObject(i).optString("value"),
                    contactService.optJSONObject(i).optString("label"),
                    contactService.optJSONObject(i).optString("icon")
                )
            )
        }

        model.setContactService(mContactService)


        if (response.has("mrzKey")) ScanMRZSharePref.getConstant(context).scanMrzKey =
            response.optString("mrzKey")

        SeatelSharePreferences.getInstance(context)?.setMainScreenData(Gson().toJson(model))
        SeatelSharePreferences.getInstance(context)
            ?.setRoamingActivation(model.getRoamingActivation())
        SeatelSharePreferences.getInstance(context)
            ?.setSpecialSimcard(model.getSpecialSimcard())
        successRespond(true)
    }

    override fun onError(error: VolleyError?) {
        super.onError(error)
        successRespond(false)
    }
}