package com.autotech.we1l.fragments

import android.content.Context
import android.os.Bundle
import android.support.v7.widget.RecyclerView
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.adapters.FavoriteAdapter
import com.autotech.we1l.app.AppLanguage
import com.autotech.we1l.app.User
import com.autotech.we1l.items.Product
import com.autotech.we1l.my_classes.BaseAdapter
import com.autotech.we1l.my_classes.BaseFragment
import com.autotech.we1l.my_classes.BaseList
import com.autotech.we1l.my_interfaces.IOnBackPressedListener
import com.autotech.we1l.tools.*
import com.autotech.we1l.tools.Language.btn_favorites
import com.autotech.we1l.tools.Language.dialog_confirm_remove_from_wish_list
import com.autotech.we1l.tools.Language.dialog_opt_no
import com.autotech.we1l.tools.Language.dialog_opt_yes
import com.autotech.we1l.tools.Language.err_no_internet_connection
import com.autotech.we1l.tools.Language.err_server_connection_error
import com.autotech.we1l.tools.Language.toast_removed_from_wishlist
import com.autotech.we1l.volley.IVolleyRequest
import com.autotech.we1l.volley.VolleyRequest
import kotlinx.android.synthetic.main.fragment_favorite.*
import kotlinx.android.synthetic.main.include_not_logged_in.*
import org.json.JSONObject

class FavoriteFragment : BaseFragment(), IOnBackPressedListener {

    lateinit var favoriteAdapter: FavoriteAdapter
    val wishListProducts = BaseList<Product>()

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

        return rootView
    }

    override fun setupViews() {

        textViewTitle.text = AppLanguage.getString(btn_favorites).toUpperCase()

        if (!User.isValid()) {
            not_logged_in_prompt.visibility = View.VISIBLE
            wish_list_rv.visibility = View.GONE

            sign_in_or_sign_up.setOnClickListener {
                val sharedPreferences = context!!.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE)
                sharedPreferences.edit().putBoolean(ATTR_IS_UNREGISTERED, false).apply()
                launchFirstActivity(activity!!)
            }
            return
        }

        favoriteAdapter = FavoriteAdapter(context!!, wishListProducts, object : BaseAdapter.OnClickListener<Product> {

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

            override fun onSpecialClick(view: View, holder: RecyclerView.ViewHolder, position: Int, product: Product) {
                MaterialDialog.Builder(context!!)
                        .content(AppLanguage.getString(dialog_confirm_remove_from_wish_list))
                        .positiveText(AppLanguage.getString(dialog_opt_yes))
                        .onPositive { _, _ ->
                            removeFromWishList(product)
                        }
                        .negativeText(AppLanguage.getString(dialog_opt_no))
                        .show()
            }
        })

        Tools.setupRV(wish_list_rv, favoriteAdapter)
    }

    override fun setupClickListeners() {
        refresh_layout.setOnRefreshListener { crucialRequests() }
    }

    private fun getWishList() {

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

        if (!User.isValid()) return

        val inputMap = HashMap<String, String>()
        inputMap[ATTR_SYSTEM_PASSCODE] = SYSTEM_PASSCODE
        inputMap[ATTR_CUSTOMER] = User.instance!!.id.toString()
        inputMap[ATTR_LANGUAGE] = User.getUserLanguageId(context!!)!!.toString()

        loading(wish_list_rv)

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

            override fun onSuccess(response: JSONObject?) {
                if (refresh_layout != null)
                    refresh_layout.isRefreshing = false
                when (response!!.getInt(ATTR_ERROR_CODE)) {
                    CODE_OK -> {
                        wishListProducts.clear()
                        val productsJSON = response.getJSONObject(ATTR_DATA).getJSONArray(ATTR_DATA)
                        for (i in 0 until productsJSON.length()) {
                            val productJSON = productsJSON.getJSONObject(i)
                            wishListProducts.add(Product(productJSON, productJSON.getInt(ATTR_CATEGORY_ID)))
                        }
                        favoriteAdapter.updateData(wishListProducts)

                        if (wishListProducts.isEmpty()) noData(wish_list_rv) else showData(wish_list_rv)
                    }
                }
            }

            override fun onFail(error: VolleyError) {
                if (refresh_layout != null)
                    refresh_layout.isRefreshing = false
                Toast.makeText(context, AppLanguage.getString(err_server_connection_error), Toast.LENGTH_LONG).show()
            }
        }).apply { requestsArray.add(this) }
    }

    private fun removeFromWishList(product: Product) {
        val inputMap = HashMap<String, String>()
        inputMap[ATTR_SYSTEM_PASSCODE] = SYSTEM_PASSCODE
        inputMap[ATTR_CUSTOMER] = User.instance!!.id.toString()
        inputMap[ATTR_PRODUCT] = product.id.toString()

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

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

            override fun onSuccess(response: JSONObject?) {

                when (response!!.getInt(ATTR_ERROR_CODE)) {
                    CODE_OK -> {
                        favoriteAdapter.removeForceRefresh(product)
                        activity?.runOnUiThread {
                            Toast.makeText(context, "${product.name} ${AppLanguage.getString(toast_removed_from_wishlist)}",
                                    Toast.LENGTH_LONG).show()
                        }
                    }
                }
            }

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

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

    }

    override fun onBackPressed(): Boolean {
        return false
    }

    override fun crucialRequests() {
        getWishList()
    }
}