package com.autotech.we1l.fragments

import android.os.Bundle
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.SearchView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import com.android.volley.VolleyError
import com.autotech.we1l.R
import com.autotech.we1l.adapters.ProductsAdapter
import com.autotech.we1l.app.AppLanguage
import com.autotech.we1l.app.User
import com.autotech.we1l.helpers.InputMap
import com.autotech.we1l.items.Product
import com.autotech.we1l.my_classes.BaseFragment
import com.autotech.we1l.my_classes.BaseAdapter
import com.autotech.we1l.my_classes.BaseList
import com.autotech.we1l.tools.*
import com.autotech.we1l.volley.IVolleyRequest
import com.autotech.we1l.volley.VolleyRequest
import kotlinx.android.synthetic.main.fragment_search.*
import org.json.JSONObject

class SearchFragment : BaseFragment() {

    private val products = BaseList<Product>()
    private lateinit var productsAdapter: ProductsAdapter


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

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        search.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
            override fun onQueryTextChange(query: String): Boolean {
                if (query.isEmpty()) {
                    productsAdapter.clear()
                    return true
                }
                search(query)
                return true
            }

            override fun onQueryTextSubmit(query: String): Boolean {
                if (query.isEmpty()) {
                    productsAdapter.clear()
                    return true
                }
                search(query)
                return true
            }
        })

        productsAdapter = ProductsAdapter(context!!, products, 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) {
                if (product.isInWishList)
                    removeFromWishList(product)
                else
                    addToWishList(product)
            }
        }, false)

        Tools.setUpRVGrid(products_rv, productsAdapter, 2)
    }

    fun search(query: String) {
        val inputMap = InputMap()

        inputMap[ATTR_SYSTEM_PASSCODE] = SYSTEM_PASSCODE
        inputMap[ATTR_TEXT] = query
        inputMap[ATTR_LANGUAGE] = User.getUserLanguageId(context!!)!!.toString()

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

            override fun onSuccess(response: JSONObject?) {
                when (response!!.getInt(ATTR_ERROR_CODE)) {
                    CODE_OK -> {
                        products.clear()
                        val searchResults = response.getJSONObject(ATTR_DATA).getJSONArray(ATTR_DATA)
                        for (i in 0 until searchResults.length()) {
                            products.add(Product(searchResults.getJSONObject(i), searchResults.getJSONObject(i).getInt(ATTR_CATEGORY_ID)))
                        }
                        productsAdapter.updateData(products)
                    }
                }
            }

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

    fun addToWishList(product: Product) {
        val inputMap = HashMap<String, String>()

        inputMap[ATTR_SYSTEM_PASSCODE] = SYSTEM_PASSCODE
        inputMap[ATTR_PRODUCT] = product.id.toString()
        inputMap[ATTR_CUSTOMER] = User.instance!!.id.toString()

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

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

                        activity?.runOnUiThread {
                            product.isInWishList = true
                            productsAdapter.notifyDataSetChanged()
                            Toast.makeText(context, "${product.name} " + AppLanguage.getString(Language.toast_added_to_wishlist), Toast.LENGTH_LONG).show()
                        }
                    }
                }
            }

            override fun onFail(error: VolleyError) {
                Toast.makeText(context, AppLanguage.getString(Language.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()

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

            override fun onSuccess(response: JSONObject?) {
                when (response!!.getInt(ATTR_ERROR_CODE)) {
                    CODE_OK -> {
                        product.isInWishList = false
                        productsAdapter.notifyDataSetChanged()
                        activity?.runOnUiThread {
                            Toast.makeText(context, "${product.name} ${AppLanguage.getString(Language.toast_removed_from_wishlist)}",
                                    Toast.LENGTH_LONG).show()
                        }
                    }
                }
            }

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

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

    }
}