package com.autotech.we1l.fragments

import android.os.Bundle
import android.support.design.widget.TextInputEditText
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.helper.ItemTouchHelper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import com.afollestad.materialdialogs.DialogAction
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.adapters.CartItemsAdapter
import com.autotech.we1l.app.AppLanguage
import com.autotech.we1l.app.User
import com.autotech.we1l.fragments.dialog_fragments.CartBillPriceDialogFragment
import com.autotech.we1l.helpers.InputMap
import com.autotech.we1l.items.CartProduct
import com.autotech.we1l.my_classes.BaseAdapter
import com.autotech.we1l.my_classes.BaseFragment
import com.autotech.we1l.tools.*
import com.autotech.we1l.tools.Language.attr_total_price
import com.autotech.we1l.tools.Language.btn_calculate_order
import com.autotech.we1l.tools.Language.dialog_loading
import com.autotech.we1l.tools.Language.dialog_opt_cancel
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_promotion_code
import com.autotech.we1l.tools.Language.err_empty_fields
import com.autotech.we1l.tools.Language.err_products_not_in_promotion
import com.autotech.we1l.tools.Language.err_promotion_expired
import com.autotech.we1l.tools.Language.err_server_connection_error
import com.autotech.we1l.tools.Language.menu_cart
import com.autotech.we1l.tools.Language.txt_Submit
import com.autotech.we1l.tools.Language.txt_v_cart_is_empty
import com.autotech.we1l.tools.Language.txt_v_no_data
import com.autotech.we1l.volley.IVolleyRequest
import com.autotech.we1l.volley.VolleyRequest
import kotlinx.android.synthetic.main.fragment_cart.*
import kotlinx.android.synthetic.main.include_loading_no_data.*
import org.json.JSONArray
import org.json.JSONObject

class CartFragment : BaseFragment(), RecyclerItemTouchHelper.RecyclerItemTouchHelperListener {

    override fun onSwiped(viewHolder: RecyclerView.ViewHolder?, direction: Int, position: Int) {
        cartItemsAdapter.removeItem(position)
        User.removeFromCart(position)
        shouldShowNoData()
        if (cartItemsAdapter.itemCount == 0)
            (activity as MainActivity).clearBadge()
    }

    // Adapters
    private lateinit var cartItemsAdapter: CartItemsAdapter


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

    override fun setupViews() {
        textViewTitle.text = AppLanguage.getString(menu_cart)
        if (User.cartProducts.isEmpty()) {
            noData(cart_items_rv, AppLanguage.getString(txt_v_cart_is_empty))
            calculate_order.visibility = View.GONE
            return
        }
        val itemTouchHelperCallback = RecyclerItemTouchHelper(0, ItemTouchHelper.START, this)

        cartItemsAdapter = CartItemsAdapter(context!!, User.cartProducts, object : BaseAdapter.OnClickListener<CartProduct> {

            override fun onClick(holder: RecyclerView.ViewHolder, position: Int, item: CartProduct) {
                launchProductDetails(context!!, item.product.id.toString())
            }

            override fun onSpecialClick(view: View, holder: RecyclerView.ViewHolder, position: Int, cartItem: CartProduct) {
                when (view.id) {
                    R.id.add -> {
                        cartItem.quantity++
                        cartItemsAdapter.notifyItemChanged(position)
                    }
                }
            }
        })

        Tools.setupRV(cart_items_rv, cartItemsAdapter)
        ItemTouchHelper(itemTouchHelperCallback).attachToRecyclerView(cart_items_rv)

        var totalPrice = 0.0
        for (i in 0 until User.cartProducts.size)
            totalPrice += User.cartProducts[i].quantity * User.cartProducts[i].product.price

        textViewTotalPrice.text = AppLanguage.getString(attr_total_price) + "$totalPrice" + " " + User.loadVisibleCurrency(context!!)?.name
        calculate_order.text = AppLanguage.getString(txt_Submit)
    }

    override fun setupClickListeners() {

        calculate_order.setOnClickListener {
            if (User.isValid()) {
                MaterialDialog.Builder(context!!)
                        .content(AppLanguage.getString(dialog_use_promotion_code))
                        .positiveText(AppLanguage.getString(dialog_opt_yes))
                        .onPositive { _, _ ->
                            val dialogView = LayoutInflater.from(context).inflate(R.layout.dialog_promotion, null, false)

                            val publicCode = dialogView.findViewById<TextInputEditText>(R.id.public_promotion_code)
                            val privateCode = dialogView.findViewById<TextInputEditText>(R.id.private_promotion_code)

                            val dialog = MaterialDialog.Builder(context!!)
                                    .customView(dialogView, true)
                                    .positiveText(AppLanguage.getString(btn_calculate_order))
                                    .negativeText(AppLanguage.getString(dialog_opt_cancel))
                                    .onNegative { _, _ ->

                                    }
                                    .show()
                            dialog.getActionButton(DialogAction.POSITIVE).setOnClickListener {
                                if (publicCode.text.toString().trim().isEmpty() || privateCode.text.toString().trim().isEmpty()) {
                                    Toast.makeText(context, AppLanguage.getString(err_empty_fields), Toast.LENGTH_LONG).show()
                                } else {
                                    calculateOrderReg(dialog, publicCode.text.toString().trim(), privateCode.text.toString().trim())
                                }
                            }
                        }
                        .negativeText(AppLanguage.getString(dialog_opt_no))
                        .onNegative { _, _ ->
                            calculateOrderReg(null, "", "")
                        }
                        .show()
            } else
                calculateOrderUnReg()
        }
    }

    override fun setupLanguages() {
        super.setupLanguages()
        //calculate_order.text = AppLanguage.getString(btn_calculate_order)

        no_data_text.text = AppLanguage.getString(txt_v_no_data)
        loading_text.text = AppLanguage.getString(dialog_loading)
    }

    override fun crucialRequests() {
        //getLocationInfo()
    }

    private fun shouldShowNoData() {
        if (cartItemsAdapter.itemCount == 0) {
            noData(null, AppLanguage.getString(txt_v_cart_is_empty))
        } else {
            showData(null)
        }
    }

    private fun calculateOrderUnReg() {
        val inputMap = InputMap()
        inputMap[ATTR_SYSTEM_PASSCODE] = SYSTEM_PASSCODE
        inputMap[ATTR_PRODUCTS] = JSONArray().apply {
            val products = User.cartProducts
            products.forEachIndexed { _, cartProduct ->
                put(cartProduct.product.id)
            }
        }.toString()
        inputMap[ATTR_QTYS] = JSONArray().apply {
            val products = User.cartProducts
            products.forEachIndexed { _, cartProduct ->
                put(cartProduct.quantity)
            }
        }.toString()

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

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

                    override fun onSuccess(response: JSONObject?) {
                        when (response!!.getInt(ATTR_ERROR_CODE)) {
                            CODE_OK -> {
                                val cartBillPriceDialogFragment = CartBillPriceDialogFragment()
                                cartBillPriceDialogFragment.arguments = Bundle().apply {
                                    putFloat(ATTR_PRICE, response.getJSONObject(ATTR_DATA).getDouble(ATTR_DATA).toFloat())
                                }
                                cartBillPriceDialogFragment.show(childFragmentManager, CartBillPriceDialogFragment.TAG)
                            }
                        }
                    }

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

                }).apply { requestsArray.add(this) }
    }

    private fun calculateOrderReg(dialog: MaterialDialog?, publicPromotionCode: String, privatePromotionCode: String) {

        val inputMap = InputMap()
        inputMap[ATTR_SYSTEM_PASSCODE] = SYSTEM_PASSCODE
        inputMap[ATTR_PRODUCTS] = JSONArray().apply {
            val products = User.cartProducts
            products.forEachIndexed { _, cartProduct ->
                put(cartProduct.product.id)
            }
        }.toString()
        inputMap[ATTR_QTYS] = JSONArray().apply {
            val products = User.cartProducts
            products.forEachIndexed { _, cartProduct ->
                put(cartProduct.quantity)
            }
        }.toString()

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

        inputMap[ATTR_PRIVATE] = privatePromotionCode
        inputMap[ATTR_PUBLIC] = publicPromotionCode

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

                    override fun onSuccess(response: JSONObject?) {
                        when (response!!.getInt(ATTR_ERROR_CODE)) {
                            CODE_OK -> {
                                dialog?.dismiss()
                                val cartBillPriceDialogFragment = CartBillPriceDialogFragment()
                                cartBillPriceDialogFragment.arguments = Bundle().apply {
                                    putFloat(ATTR_PRICE, response.getJSONObject(ATTR_DATA).getJSONObject(ATTR_DATA)
                                            .getDouble(ATTR_FINAL_BILL).toFloat())
                                    putString(ATTR_PUBLIC_CODE, publicPromotionCode)
                                    putString(ATTR_PRIVATE_CODE, privatePromotionCode)
                                }

                                val fragmentTransaction = fragmentManager?.beginTransaction()
                                fragmentTransaction?.add(cartBillPriceDialogFragment, CartBillPriceDialogFragment.TAG)
                                fragmentTransaction?.commit()
                            }
                            CODE_PROMOTION_EXPIRED -> {
                                Toast.makeText(context, AppLanguage.getString(err_promotion_expired), Toast.LENGTH_LONG).show()
                                dialog?.dismiss()
                            }
                            CODE_PRODUCTS_ARENT_IN_PROMOTION -> {
                                Toast.makeText(context, AppLanguage.getString(err_products_not_in_promotion), Toast.LENGTH_LONG).show()
                                dialog?.dismiss()
                            }
                        }
                    }

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

                }).apply { requestsArray.add(this) }
    }

    override fun onResume() {
        super.onResume()
        setupViews()
    }
}