package com.autotech.we1l.activities

import android.os.Bundle
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.SearchView
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import com.android.volley.VolleyError
import com.autotech.we1l.R
import com.autotech.we1l.my_classes.BaseActivity
import com.autotech.we1l.my_classes.BaseList
import kotlinx.android.synthetic.main.activity_search.*
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.BaseAdapter
import com.autotech.we1l.tools.*
import com.autotech.we1l.tools.Language.err_server_connection_error
import com.autotech.we1l.tools.Language.toast_added_to_wishlist
import com.autotech.we1l.tools.Language.toast_removed_from_wishlist
import com.autotech.we1l.volley.IVolleyRequest
import com.autotech.we1l.volley.VolleyRequest
import org.json.JSONObject


class SearchActivity : BaseActivity() {

    // Lists
    private val products = BaseList<Product>()

    // Adapters
    private lateinit var productsAdapter: ProductsAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_search)
        setSupportActionBar(toolbar)

        doAll()
    }

    override fun setupViews() {

        supportActionBar?.setDisplayHomeAsUpEnabled(true)

        search.queryHint = AppLanguage.getString(Language.menu_search)
        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(this, products, object : BaseAdapter.OnClickListener<Product> {
            override fun onClick(holder: RecyclerView.ViewHolder, position: Int, product: Product) {
                launchProductDetails(this@SearchActivity, 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)
    }

    override fun setupClickListeners() {

    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        when (item?.itemId) {
            android.R.id.home -> onBackPressed()

        }
        return super.onOptionsItemSelected(item)
    }

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

        inputMap[ATTR_SYSTEM_PASSCODE] = SYSTEM_PASSCODE
        inputMap[ATTR_TEXT] = query
        inputMap[ATTR_LANGUAGE] = User.getUserLanguageId(applicationContext!!)!!.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(this@SearchActivity, AppLanguage.getString(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 -> {

                        runOnUiThread {
                            product.isInWishList = true
                            productsAdapter.notifyDataSetChanged()
                            Toast.makeText(this@SearchActivity, "${product.name} " + AppLanguage.getString(toast_added_to_wishlist), Toast.LENGTH_LONG).show()
                        }
                    }
                }
            }

            override fun onFail(error: VolleyError) {
                Toast.makeText(this@SearchActivity, 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()

        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()
                        runOnUiThread {
                            Toast.makeText(this@SearchActivity, "${product.name} ${AppLanguage.getString(toast_removed_from_wishlist)}",
                                    Toast.LENGTH_LONG).show()
                        }
                    }
                }
            }

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

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

    }

}
