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.android.volley.VolleyError
import com.autotech.we1l.R
import com.autotech.we1l.adapters.OrdersAdapter
import com.autotech.we1l.app.AppLanguage
import com.autotech.we1l.app.User
import com.autotech.we1l.helpers.InputMap
import com.autotech.we1l.items.Order
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.err_no_internet_connection
import com.autotech.we1l.tools.Language.nav_my_orders
import com.autotech.we1l.volley.IVolleyRequest
import com.autotech.we1l.volley.VolleyRequest
import kotlinx.android.synthetic.main.fragment_user_orders.*
import kotlinx.android.synthetic.main.include_loading_no_data.*
import kotlinx.android.synthetic.main.include_not_logged_in.*
import org.json.JSONObject
import java.util.*

class UserOrdersFragment : BaseFragment(), IOnBackPressedListener {

    // Lists:
    private val orders = BaseList<Order>()

    // Adapters:
    private lateinit var ordersAdapter: OrdersAdapter

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

    override fun setupViews() {
        textViewTitle.text = AppLanguage.getString(nav_my_orders)
        if (!User.isValid()) {
            not_logged_in_prompt.visibility = View.VISIBLE
            my_orders_rv.visibility = View.GONE
            no_data_layout.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
        }

        ordersAdapter = OrdersAdapter(context!!, orders, object : BaseAdapter.OnClickListener<Order> {
            override fun onSpecialClick(view: View, holder: RecyclerView.ViewHolder, position: Int, order: Order) {
                when (view.id) {
                    R.id.track_order -> {
                        launchTrackOrders(context!!, order)
                    }
                    R.id.order_details -> {
                        launchOrderDetails(context!!, order)
                    }
                }
            }
        })

        Tools.setupRV(my_orders_rv, ordersAdapter)
    }

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

    private fun getMyOrders() {
        val inputMap = InputMap()
        inputMap[ATTR_SYSTEM_PASSCODE] = SYSTEM_PASSCODE
        inputMap[ATTR_CUSTOMER] = User.instance?.id.toString()
        inputMap[ATTR_LANGUAGE] = User.getUserLanguageId(context!!)!!.toString()

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

        if (!User.isValid()) return

        loading(my_orders_rv)

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

                    override fun onSuccess(response: JSONObject?) {
                        if (refresh_layout != null)
                            refresh_layout.isRefreshing = false
                        when (response!!.getInt(ATTR_ERROR_CODE)) {
                            CODE_OK -> {
                                orders.clear()
                                val data = response.getJSONObject(ATTR_DATA).getJSONArray(ATTR_DATA)

                                for (i in 0 until data.length()) {
                                    orders.add(Order(data.getJSONObject(i)))
                                }
                                Collections.reverse(orders)
                                ordersAdapter.updateData(orders)

                                if (orders.isEmpty()) noData(my_orders_rv) else showData(my_orders_rv)
                            }
                        }
                    }

                    override fun onFail(error: VolleyError) {
                        if (refresh_layout != null)
                            refresh_layout.isRefreshing = false
                        noData(my_orders_rv, getString(R.string.prompt_please_retry))
                        Toast.makeText(context, R.string.err_server_connection_error, Toast.LENGTH_LONG).show()
                    }
                })
    }


    override fun onBackPressed(): Boolean {
        return false
    }

    override fun crucialRequests() {
        getMyOrders()
    }

}