package com.autotech.we1l.fragments

import android.annotation.SuppressLint
import android.content.Context.LOCATION_SERVICE
import android.content.Intent
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.support.v4.app.DialogFragment
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import com.afollestad.materialdialogs.MaterialDialog
import com.android.volley.VolleyError
import com.autotech.we1l.R
import com.autotech.we1l.activities.MainActivity
import com.autotech.we1l.app.AppLanguage
import com.autotech.we1l.app.User
import com.autotech.we1l.fragments.dialog_fragments.PaymentFragment
import com.autotech.we1l.helpers.InputMap
import com.autotech.we1l.helpers.AnimatorUtils
import com.autotech.we1l.items.*
import com.autotech.we1l.my_classes.BaseFragment
import com.autotech.we1l.my_classes.BaseList
import com.autotech.we1l.tools.*
import com.autotech.we1l.tools.Language.attr_address
import com.autotech.we1l.tools.Language.attr_city
import com.autotech.we1l.tools.Language.attr_country
import com.autotech.we1l.tools.Language.attr_location
import com.autotech.we1l.tools.Language.attr_payment
import com.autotech.we1l.tools.Language.attr_personal_information
import com.autotech.we1l.tools.Language.attr_region
import com.autotech.we1l.tools.Language.attr_remaining_is
import com.autotech.we1l.tools.Language.attr_select_location_from
import com.autotech.we1l.tools.Language.attr_shipping_company
import com.autotech.we1l.tools.Language.attr_total_price
import com.autotech.we1l.tools.Language.btn_cash
import com.autotech.we1l.tools.Language.btn_configure_payment
import com.autotech.we1l.tools.Language.btn_favorites
import com.autotech.we1l.tools.Language.btn_gps
import com.autotech.we1l.tools.Language.btn_manually
import com.autotech.we1l.tools.Language.btn_place_order
import com.autotech.we1l.tools.Language.dialog_getting_location
import com.autotech.we1l.tools.Language.dialog_loading
import com.autotech.we1l.tools.Language.dialog_opt_no
import com.autotech.we1l.tools.Language.dialog_opt_yes
import com.autotech.we1l.tools.Language.dialog_use_store_credit
import com.autotech.we1l.tools.Language.err_address_not_specified
import com.autotech.we1l.tools.Language.err_email_address_invalid
import com.autotech.we1l.tools.Language.err_generic_error
import com.autotech.we1l.tools.Language.err_no_internet_connection
import com.autotech.we1l.tools.Language.err_no_location
import com.autotech.we1l.tools.Language.err_no_shipping_company
import com.autotech.we1l.tools.Language.err_not_logged_in_missing_info
import com.autotech.we1l.tools.Language.err_server_connection_error
import com.autotech.we1l.tools.Language.hint_email
import com.autotech.we1l.tools.Language.hint_full_name
import com.autotech.we1l.tools.Language.hint_mobile
import com.autotech.we1l.tools.Language.hint_phone
import com.autotech.we1l.tools.Language.txt_v_no_store_credit
import com.autotech.we1l.tools.Language.txt_v_store_credit_covered
import com.autotech.we1l.volley.IVolleyRequest
import com.autotech.we1l.volley.VolleyRequest
import kotlinx.android.synthetic.main.fragment_check_out.*
import org.json.JSONArray
import org.json.JSONObject

class CheckOutFragment : BaseFragment() {

    // Consts:
    private val LOCATION_MY_PLACE = 0
    private val LOCATION_GPS = 1
    private val LOCATION_MANUAL = 2

    // Lists
    private val countries = BaseList<Country>()
    private val currencies = BaseList<Currency>()
    private val myFavoriteLocations = BaseList<BasePlace>()
    private val shippingCompanies = BaseList<ShippingCompany>()

    // Indexes
    private var countryIndex = -1
    private var cityIndex = -1
    private var regionIndex = -1
    private var currencyIndex = -1
    private var myFavoriteLocationIndex = -1
    private var shippingCompanyIndex = -1
    private var locationType = LOCATION_MY_PLACE

    // Vars
    private var useStoreCredit = false
    private lateinit var publicCode: String
    private lateinit var privateCode: String
    private var lon: String? = null
    private var lat: String? = null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        rootView = layoutInflater.inflate(R.layout.fragment_check_out, container, false)
        return rootView
    }

    @SuppressLint("SetTextI18n")
    override fun setupViews() {

        publicCode = arguments!!.getString(ATTR_PUBLIC_CODE)!!
        privateCode = arguments!!.getString(ATTR_PRIVATE_CODE)!!

        if (User.isValid()) {
            full_name_layout.visibility = View.GONE
            phone_layout.visibility = View.GONE
            mobile_layout.visibility = View.GONE
            email_layout.visibility = View.GONE
            getMyPlaces()
        } else {
            location_favorites.visibility = View.GONE
        }

        total_price.text = "${arguments!!.getFloat(ATTR_PRICE)} ${User.loadVisibleCurrency(context!!)!!.name}"

        if (!isNetworkAvailable(context!!)) {
            Toast.makeText(context, AppLanguage.getString(err_no_internet_connection), Toast.LENGTH_LONG).show()
            return
        }
        if (!User.isValid()) {
            configure_payment.visibility = View.GONE
            payment_options.visibility = View.VISIBLE
            favorite_locations.visibility = View.GONE
            select_location_title.visibility = View.GONE
        } else {
            personal_info_title.visibility = View.GONE
        }
    }

    //define the listener
    private val locationListener: LocationListener = object : LocationListener {
        override fun onLocationChanged(location: Location) {
            lon = location.longitude.toString()
            lat = location.latitude.toString()
            getting_location.text = "$lon $lat"
        }

        override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {}
        override fun onProviderEnabled(provider: String) {}
        override fun onProviderDisabled(provider: String) {}
    }
    private var locationManager: LocationManager? = null

    override fun setupClickListeners() {

        location_favorites.setOnClickListener {
            location_favorites_radio.isChecked = true
            location_gps_radio.isChecked = false
            location_manual_radio.isChecked = false

            if (favorite_locations.visibility == View.GONE) {
                favorite_locations.visibility = View.VISIBLE
                favorite_locations.setDropdownMaxHeight(50)
            }
            if (getting_location.visibility == View.VISIBLE) {
                getting_location.visibility = View.GONE
            }
            if (location_manual_layout.visibility == View.VISIBLE) {
                location_manual_layout.visibility = View.GONE
            }

            locationType = LOCATION_MY_PLACE
        }

        location_gps.setOnClickListener {
            location_favorites_radio.isChecked = false
            location_gps_radio.isChecked = true
            location_manual_radio.isChecked = false
            val permissions = arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION)
            ActivityCompat.requestPermissions(this.requireActivity(), permissions, 0)
            locationManager = this.context?.getSystemService(LOCATION_SERVICE) as LocationManager?

            try {
                // Request location updates
                locationManager?.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000L, 100f, locationListener)
            } catch (ex: SecurityException) {
                Log.d("myTag", "Security Exception, no location available")
            }

            if (favorite_locations.visibility == View.VISIBLE) {
                favorite_locations.visibility = View.GONE
            }
            if (getting_location.visibility == View.GONE) {
                getting_location.visibility = View.VISIBLE
            }
            if (location_manual_layout.visibility == View.VISIBLE) {
                location_manual_layout.visibility = View.GONE
            }

            locationType = LOCATION_GPS
        }

        location_manual.setOnClickListener {
            location_favorites_radio.isChecked = false
            location_gps_radio.isChecked = false
            location_manual_radio.isChecked = true

            if (favorite_locations.visibility == View.VISIBLE) {
                favorite_locations.visibility = View.GONE
            }
            if (getting_location.visibility == View.VISIBLE) {
                getting_location.visibility = View.GONE
            }
            if (location_manual_layout.visibility == View.GONE) {
                location_manual_layout.visibility = View.VISIBLE
            }
            locationType = LOCATION_MANUAL
        }

        country_spinner.setOnItemSelectedListener { _, position, _, _ ->
            countryIndex = position

            city_spinner.setItems(countries[countryIndex].cities.names)

            region_spinner.setItems(countries[countryIndex].cities[0].regions.names)

            cityIndex = -1
            regionIndex = -1
        }

        city_spinner.setOnItemSelectedListener { _, position, _, _ ->
            cityIndex = position

            region_spinner.setItems(countries[countryIndex].cities[cityIndex].regions.names)

            regionIndex = -1
        }

        region_spinner.setOnItemSelectedListener { _, position, _, _ -> regionIndex = position }

        favorite_locations.setOnItemSelectedListener { _, position, _, _ ->
            myFavoriteLocationIndex = position
        }

        cash_payment.setOnClickListener {
            cash_payment_radio.isChecked = true
//            gateway_payment_radio.isChecked = false
        }

//        gateway_payment.setOnClickListener {
//            cash_payment_radio.isChecked = false
//            gateway_payment_radio.isChecked = true
//        }

        shipping_companies_spinner.setOnItemSelectedListener { _, position, _, _ ->
            shippingCompanyIndex = position
        }

        configure_payment.setOnClickListener {
            MaterialDialog.Builder(context!!)
                    .content(AppLanguage.getString(dialog_use_store_credit))
                    .positiveText(AppLanguage.getString(dialog_opt_yes))
                    .onPositive { _, _ ->
                        getStoreCredit()
                        useStoreCredit = true
                    }
                    .negativeText(AppLanguage.getString(dialog_opt_no))
                    .onNegative { _, _ ->
                        useStoreCredit = false
                    }
                    .show()
        }

        place_order.setOnClickListener {
            if (User.isValid()) {
                MaterialDialog.Builder(context!!)
                        .content(AppLanguage.getString(dialog_use_store_credit))
                        .positiveText(AppLanguage.getString(dialog_opt_yes))
                        .onPositive { _, _ ->
                            useStoreCredit = true
                            setOrderReg()
                        }
                        .negativeText(AppLanguage.getString(dialog_opt_no))
                        .onNegative { _, _ ->
                            useStoreCredit = false
                            setOrderReg()
                        }
                        .show()
            } else {
                setOrderUnreg()
            }
        }
    }

    override fun setupLanguages() {
        super.setupLanguages()
        personal_info_title.text = AppLanguage.getString(attr_personal_information)
        location_title.text = AppLanguage.getString(attr_location)

        favorite_locations_text.text = AppLanguage.getString(btn_favorites)
        gps_title.text = AppLanguage.getString(btn_gps)
        location_manual_title.text = AppLanguage.getString(btn_manually)
        select_location_title.text = AppLanguage.getString(attr_select_location_from)

        getting_location.text = AppLanguage.getString(dialog_getting_location)

        shipping_company_title.text = AppLanguage.getString(attr_shipping_company)

        total_price_title.text = AppLanguage.getString(attr_total_price)

        payment_title.text = AppLanguage.getString(attr_payment)

        configure_payment.text = AppLanguage.getString(btn_configure_payment)

        store_credit_covered_text.text = AppLanguage.getString(txt_v_store_credit_covered)
        remaining_is.text = AppLanguage.getString(attr_remaining_is)

        cash_title.text = AppLanguage.getString(btn_cash)

        place_order.text = AppLanguage.getString(btn_place_order)

        full_name_layout.hint = AppLanguage.getString(hint_full_name)
        phone_layout.hint = AppLanguage.getString(hint_phone)
        mobile_layout.hint = AppLanguage.getString(hint_mobile)
        email_layout.hint = AppLanguage.getString(hint_email)
        address_layout.hint = AppLanguage.getString(attr_address)
        country_spinner.hint = AppLanguage.getString(attr_country)
        city_spinner.hint = AppLanguage.getString(attr_city)
        region_spinner.hint = AppLanguage.getString(attr_region)
    }

    override fun crucialRequests() {
        getPlaces()
        getShippingCompanies()
    }

    private fun setOrderReg() {

        if (!isNetworkAvailable(context!!)) {
            Toast.makeText(context, AppLanguage.getString(err_no_internet_connection), Toast.LENGTH_LONG).show()
            return
        }

        when {
            (locationType == LOCATION_MANUAL && regionIndex == -1) ||
                    (locationType == LOCATION_MY_PLACE && myFavoriteLocationIndex == -1) -> {
                Toast.makeText(context, AppLanguage.getString(err_no_location), Toast.LENGTH_LONG).show()
                return
            }
            /*locationType == LOCATION_GPS -> {
                Toast.makeText(context, "Not yet implemented", Toast.LENGTH_LONG).show()
                return
            }*/
            shippingCompanyIndex == -1 -> {
                Toast.makeText(context, AppLanguage.getString(err_no_shipping_company), Toast.LENGTH_LONG).show()
                return
            }
            address.text!!.trim().isEmpty() -> {
                Toast.makeText(context, AppLanguage.getString(err_address_not_specified), Toast.LENGTH_LONG).show()
                return
            }
        }

        val inputMap = InputMap()
        inputMap[ATTR_SYSTEM_PASSCODE] = SYSTEM_PASSCODE

        inputMap[ATTR_CUSTOMER] = User.instance!!.id.toString()

        inputMap[ATTR_ADDRESS] = address.text!!.trim().toString()
        if (locationType == LOCATION_GPS) {
            inputMap[ATTR_LAT] = lat.toString()
            inputMap[ATTR_LON] = lon.toString()
        }

        if (locationType == LOCATION_MANUAL) {
            inputMap[ATTR_REGION] = countries[countryIndex].cities[cityIndex].regions[regionIndex].id.toString()

        } else if (locationType == LOCATION_MY_PLACE) {

            inputMap[ATTR_REGION] = myFavoriteLocations[myFavoriteLocationIndex].regionId.toString()
        }

        val productIds = JSONArray()
        val quantities = JSONArray()
        val colorsIds = JSONArray()

        User.cartProducts.forEachIndexed { _, cartProduct ->
            productIds.put(cartProduct.product.id)
            quantities.put(cartProduct.quantity)
            colorsIds.put(cartProduct.colorId)
        }

        inputMap[ATTR_PRODUCTS] = productIds.toString()
        inputMap[ATTR_QTYS] = quantities.toString()
        inputMap[ATTR_COLORS] = colorsIds.toString()

        inputMap[ATTR_CURRENCY] = User.loadVisibleCurrency(context!!)!!.id.toString()

        inputMap[ATTR_STORE_CREDIT] = (if (useStoreCredit) 1 else 0).toString()

        inputMap[ATTR_SHIPPING_COMPANY] = (shippingCompanies[shippingCompanyIndex]).id.toString()

        inputMap[ATTR_PUBLIC] = publicCode
        inputMap[ATTR_PRIVATE] = privateCode

        val progressDialog = MaterialDialog.Builder(context!!)
                .progress(true, 100)
                .content(AppLanguage.getString(dialog_loading))
                .cancelable(false)
                .show()

        VolleyRequest.getInstance().post(REQUEST_SET_ORDER, inputMap, object : IVolleyRequest {

            override fun onSuccess(response: JSONObject?) {
                progressDialog.dismiss()
                when (response!!.getInt(ATTR_ERROR_CODE)) {
                    CODE_OK -> {

                        if (response.getJSONObject(ATTR_DATA).getJSONObject(ATTR_DATA).getString("url").isEmpty()) {
                            User.deleteCart()
                            activity?.finishAffinity()
                            startActivity(Intent(activity, MainActivity::class.java))
                            return
                        }

                        val paymentFragment = PaymentFragment().apply {
                            arguments = Bundle().apply {
                                putString(ATTR_URL, response.getJSONObject(ATTR_DATA).getJSONObject(ATTR_DATA).getString("url"))
                            }
                            setStyle(DialogFragment.STYLE_NO_TITLE, R.style.DialogFragment)
                        }

                        paymentFragment.show(childFragmentManager, "OrderResultDialogFragment")
                    }
                    else -> Toast.makeText(context, AppLanguage.getString(err_generic_error), Toast.LENGTH_LONG).show()
                }
            }

            override fun onFail(error: VolleyError) {
                progressDialog.dismiss()
                Toast.makeText(context, AppLanguage.getString(err_server_connection_error), Toast.LENGTH_LONG).show()
            }
        }).apply { requestsArray.add(this) }
    }

    private fun setOrderUnreg() {

        if (!isNetworkAvailable(context!!)) {
            Toast.makeText(context, AppLanguage.getString(err_no_internet_connection), Toast.LENGTH_LONG).show()
            return
        }

        when {
            (locationType == LOCATION_MANUAL && regionIndex == -1) -> {
                Toast.makeText(context, AppLanguage.getString(err_no_location), Toast.LENGTH_LONG).show()
                return
            }
            /*locationType == LOCATION_GPS -> {
                Toast.makeText(context, "Not yet implemented", Toast.LENGTH_LONG).show()
                return
            }*/
            shippingCompanyIndex == -1 -> {
                Toast.makeText(context, AppLanguage.getString(err_no_shipping_company), Toast.LENGTH_LONG).show()
                return
            }
            full_name.text!!.trim().isEmpty() || phone.text!!.trim().isEmpty()
                    || mobile.text!!.trim().isEmpty() || email.text.toString().trim().isEmpty() -> {
                Toast.makeText(context, AppLanguage.getString(err_not_logged_in_missing_info), Toast.LENGTH_LONG).show()
                return
            }
            address.text!!.trim().isEmpty() -> {
                Toast.makeText(context, AppLanguage.getString(err_address_not_specified), Toast.LENGTH_LONG).show()
                return
            }
            !Tools.isEmailValid(email.text.toString().trim()) -> {
                Toast.makeText(context, AppLanguage.getString(err_email_address_invalid), Toast.LENGTH_LONG).show()
                return
            }
        }

        val inputMap = InputMap()
        inputMap[ATTR_SYSTEM_PASSCODE] = SYSTEM_PASSCODE

        inputMap[ATTR_NAME] = full_name.text!!.trim().toString()
        inputMap[ATTR_PHONE] = phone.text!!.trim().toString()
        inputMap[ATTR_MOBILE] = mobile.text!!.trim().toString()
        inputMap[ATTR_EMAIL] = email.text!!.trim().toString()
        inputMap[ATTR_LAT] = lat.toString()
        inputMap[ATTR_LON] = lon.toString()
        inputMap[ATTR_ADDRESS] = address.text!!.trim().toString()

        inputMap[ATTR_REGION] = countries[countryIndex].cities[cityIndex].regions[regionIndex].id.toString()

        val productIds = JSONArray()
        val quantities = JSONArray()
        val colorsIds = JSONArray()

        User.cartProducts.forEachIndexed { _, cartProduct ->
            productIds.put(cartProduct.product.id)
            quantities.put(cartProduct.quantity)
            colorsIds.put(cartProduct.colorId)
        }

        inputMap[ATTR_PRODUCTS] = productIds.toString()
        inputMap[ATTR_QTYS] = quantities.toString()
        inputMap[ATTR_COLORS] = colorsIds.toString()

        inputMap[ATTR_CURRENCY] = User.loadVisibleCurrency(context!!)!!.id.toString()

        inputMap[ATTR_STORE_CREDIT] = (if (useStoreCredit) 1 else 0).toString()

        inputMap[ATTR_SHIPPING_COMPANY] = (shippingCompanies[shippingCompanyIndex]).id.toString()

        inputMap[ATTR_PUBLIC] = publicCode
        inputMap[ATTR_PRIVATE] = privateCode

        val progressDialog = MaterialDialog.Builder(context!!)
                .progress(true, 100)
                .content(AppLanguage.getString(dialog_loading))
                .cancelable(false)
                .show()

        VolleyRequest.getInstance().post(REQUEST_SET_ORDER_UNREG, inputMap, object : IVolleyRequest {

            override fun onSuccess(response: JSONObject?) {
                progressDialog.dismiss()
                when (response!!.getInt(ATTR_ERROR_CODE)) {
                    CODE_OK -> {

                        if (response.getJSONObject(ATTR_DATA).getJSONObject(ATTR_DATA).getString("url").isEmpty()) {
                            User.deleteCart()
                            activity?.finishAffinity()
                            startActivity(Intent(activity, MainActivity::class.java))
                            return
                        }

                        val data = response.getJSONObject(ATTR_DATA).getJSONObject(ATTR_DATA)

                        val paymentFragment = PaymentFragment().apply {
                            arguments = Bundle().apply {
                                putString(ATTR_URL, response.getJSONObject(ATTR_DATA).getJSONObject(ATTR_DATA).getString("url"))
                            }
                            setStyle(DialogFragment.STYLE_NO_TITLE, R.style.DialogFragment)
                        }

                        paymentFragment.show(childFragmentManager, "OrderResultDialogFragment")
                    }
                    else -> Toast.makeText(context, AppLanguage.getString(err_generic_error), Toast.LENGTH_LONG).show()
                }
            }

            override fun onFail(error: VolleyError) {
                progressDialog.dismiss()
                Toast.makeText(context, AppLanguage.getString(err_server_connection_error), Toast.LENGTH_LONG).show()
            }
        }).apply { requestsArray.add(this) }
    }

    private fun getPlaces() {

        val inputMap = HashMap<String, String>()
        inputMap[ATTR_SYSTEM_PASSCODE] = SYSTEM_PASSCODE

        VolleyRequest.getInstance().post(REQUEST_GET_PLACES, inputMap, object : IVolleyRequest {

            override fun onSuccess(response: JSONObject?) {

                when (response!!.getInt(ATTR_ERROR_CODE)) {
                    CODE_OK -> {
                        countries.clear()

                        val data = response.getJSONObject(ATTR_DATA).getJSONArray(ATTR_DATA)
                        for (i in 0 until data.length()) {
                            countries.add(Country(data.getJSONObject(i)))
                        }

                        countryIndex = 0
                        cityIndex = 0
                        regionIndex = 0

                        country_spinner.setItems(countries.names)
                        city_spinner.setItems(countries[0].cities.names)
                        region_spinner.setItems(countries[0].cities[0].regions.names)
                    }
                }
            }

            override fun onFail(error: VolleyError) {
                Toast.makeText(context, AppLanguage.getString(err_server_connection_error), Toast.LENGTH_LONG).show()
            }
        }).apply { requestsArray.add(this) }
    }

    private fun getCurrencies() {
        val inputMap = HashMap<String, String>()
        inputMap[ATTR_SYSTEM_PASSCODE] = SYSTEM_PASSCODE

        VolleyRequest.getInstance().post(REQUEST_GET_CURRENCIES, inputMap, object : IVolleyRequest {

            override fun onSuccess(response: JSONObject?) {
                when (response!!.getInt(ATTR_ERROR_CODE)) {
                    CODE_OK -> {
                        currencies.clear()

                        val data = response.getJSONObject(ATTR_DATA).getJSONArray(ATTR_DATA)
                        for (i in 0 until data.length()) {
                            currencies.add(Currency(data.getJSONObject(i)))
                        }

                        currencyIndex = 0
                    }
                }
            }

            override fun onFail(error: VolleyError) {
                Toast.makeText(context, AppLanguage.getString(err_server_connection_error), Toast.LENGTH_LONG).show()
            }
        }).apply { requestsArray.add(this) }
    }

    private fun getMyPlaces() {
        val inputMap = InputMap()
        inputMap[ATTR_SYSTEM_PASSCODE] = SYSTEM_PASSCODE
        inputMap[ATTR_CUSTOMER] = User.instance?.id.toString()

        VolleyRequest.getInstance()
                .post(REQUEST_MY_ADDRESSES, inputMap, object : IVolleyRequest {

                    override fun onSuccess(response: JSONObject?) {
                        when (response!!.getInt(ATTR_ERROR_CODE)) {
                            CODE_OK -> {
                                myFavoriteLocations.clear()
                                val data = response.getJSONObject(ATTR_DATA).getJSONArray(ATTR_DATA)
                                for (i in 0 until data.length()) {
                                    val myPlaceJSON = data.getJSONObject(i)
                                    myFavoriteLocations.add(BasePlace(myPlaceJSON))
                                }
                                if (myFavoriteLocations.isNotEmpty())
                                    myFavoriteLocationIndex = 0

                                favorite_locations.setItems(myFavoriteLocations.names)
                            }
                        }
                    }

                    override fun onFail(error: VolleyError) {
                        Toast.makeText(context, AppLanguage.getString(err_server_connection_error), Toast.LENGTH_LONG).show()
                    }
                }).apply { requestsArray.add(this) }
    }

    private fun getShippingCompanies() {
        val inputMap = InputMap()
        inputMap[ATTR_SYSTEM_PASSCODE] = SYSTEM_PASSCODE

        VolleyRequest.getInstance()
                .post(REQUEST_SHIPPING_COMPANY, inputMap, object : IVolleyRequest {
                    override fun onSuccess(response: JSONObject?) {
                        when (response!!.getInt(ATTR_ERROR_CODE)) {
                            CODE_OK -> {
                                shippingCompanies.clear()
                                val data = response.getJSONObject(ATTR_DATA).getJSONArray(ATTR_DATA)
                                for (i in 0 until data.length()) {
                                    shippingCompanies.add(ShippingCompany(data.getJSONObject(i)))
                                }

                                shippingCompanyIndex = 0

                                shipping_companies_spinner.setItems(shippingCompanies.names)
                            }
                        }
                    }

                    override fun onFail(error: VolleyError) {
                        Toast.makeText(context, AppLanguage.getString(err_server_connection_error), Toast.LENGTH_LONG).show()
                    }
                }).apply { requestsArray.add(this) }
    }

    private fun getStoreCredit() {
        if (!isNetworkAvailable(context!!)) {
            Toast.makeText(context, AppLanguage.getString(err_no_internet_connection), Toast.LENGTH_LONG).show()
            return
        }

        val progressDialog = MaterialDialog.Builder(context!!)
                .progress(true, 100)
                .content(AppLanguage.getString(dialog_loading))
                .cancelable(false)
                .show()

        VolleyRequest.getInstance()
                .post(REQUEST_GET_STORE_CREDIT, InputMap().apply {
                    put(ATTR_SYSTEM_PASSCODE, SYSTEM_PASSCODE)
                    put(ATTR_CUSTOMER, User.instance!!.id.toString())
                    put(ATTR_CURRENCY, User.loadVisibleCurrency(context!!)!!.id.toString())
                }, object : IVolleyRequest {

                    @SuppressLint("SetTextI18n")
                    override fun onSuccess(response: JSONObject?) {
                        progressDialog.dismiss()
                        when (response!!.getInt(ATTR_ERROR_CODE)) {
                            CODE_OK -> {
                                val price = arguments!!.getFloat(ATTR_PRICE)
                                val storeCredit = response.getJSONObject(ATTR_DATA).getDouble(ATTR_DATA)
                                store_credit_coverage_info.visibility = View.VISIBLE
                                payment_options.visibility = View.VISIBLE
                                AnimatorUtils.hide(configure_payment)
                                when {
                                    storeCredit > price -> {
                                        store_credit_covered.text = "$price ${User.loadVisibleCurrency(context!!)!!.name}"
                                        remaining.text = "0 ${User.loadVisibleCurrency(context!!)!!.name}"
                                    }
                                    storeCredit < price && storeCredit != 0.toDouble() -> {
                                        store_credit_covered.text = "$storeCredit ${User.loadVisibleCurrency(context!!)!!.name}"
                                        remaining.text = "${price - storeCredit} ${User.loadVisibleCurrency(context!!)!!.name}"
                                    }
                                    storeCredit == 0.toDouble() -> {
                                        store_credit_covered_text.text = AppLanguage.getString(txt_v_no_store_credit)
                                        store_credit_covered.visibility = View.GONE
                                        remaining_is.visibility = View.GONE
                                        remaining.visibility = View.GONE
                                    }
                                }
                            }
                        }
                    }

                    override fun onFail(errorListener: VolleyError?) {
                        progressDialog.dismiss()
                        Toast.makeText(context, AppLanguage.getString(err_server_connection_error), Toast.LENGTH_LONG).show()
                    }
                }).apply { requestsArray.add(this) }
    }

}