package com.autotech.we1l.fragments

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import android.view.*
import android.widget.Toast
import com.android.volley.VolleyError
import com.autotech.we1l.R
import com.autotech.we1l.adapters.*
import com.autotech.we1l.app.AppLanguage
import com.autotech.we1l.app.User
import com.autotech.we1l.helpers.InputMap
import com.autotech.we1l.items.*
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.attr_today_s_hot_deals
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.menu_search
import com.autotech.we1l.tools.Language.prompt_please_retry
import com.autotech.we1l.tools.Language.txt_today_trending
import com.autotech.we1l.tools.Language.txt_v_best_sellers
import com.autotech.we1l.tools.Language.txt_v_new_arrival
import com.autotech.we1l.volley.IVolleyRequest
import com.autotech.we1l.volley.VolleyRequest
import kotlinx.android.synthetic.main.fragment_home.*
import org.json.JSONArray
import org.json.JSONObject


class HomeFragment : BaseFragment(), IOnBackPressedListener {

    private val sliderImages = BaseList<SlideImage>()

    private lateinit var sliderImagesAdapter: SliderImagesAdapter

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

    override fun setupViews() {
        activity?.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)
        best_seller_text.text = AppLanguage.getString(txt_v_best_sellers)
        new_arrival_text.text = AppLanguage.getString(txt_v_new_arrival)
        todays_trending_text.text = AppLanguage.getString(txt_today_trending)
        sliderImagesAdapter = SliderImagesAdapter(context!!, sliderImages)
        //circleIndicator.setViewPager()
        Tools.setupRVHorizontal(slider_images_rv, sliderImagesAdapter)

        scrollSlider(0)
    }

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

        imageViewSearch.setOnClickListener { launchSearchActivity(context!!) }
        editTextSearch.setOnClickListener { launchSearchActivity(context!!) }
    }

    override fun setupLanguages() {
        super.setupLanguages()
        todays_hot_deals_title.text = AppLanguage.getString(attr_today_s_hot_deals)
        editTextSearch.hint = AppLanguage.getString(menu_search)
    }

    private fun getSliderImages() {
        VolleyRequest.getInstance()
                .post(REQUEST_GET_SLIDER_IMAGES, InputMap().apply {
                    put(ATTR_SYSTEM_PASSCODE, SYSTEM_PASSCODE)
                }, object : IVolleyRequest {

                    override fun onSuccess(response: JSONObject?) {
                        if (refresh_layout != null)
                            refresh_layout.isRefreshing = false
                        when (response!!.getInt(ATTR_ERROR_CODE)) {
                            CODE_OK -> {
                                sliderImages.clear()
                                val data = response.getJSONObject(ATTR_DATA).getJSONArray(ATTR_DATA)
                                for (i in 0 until data.length()) {
                                    sliderImages.add(SlideImage(data.getJSONObject(i)))
                                }

                                if (!isVisible) return

                                sliderImagesAdapter.updateData(sliderImages)
                            }
                        }
                    }

                    override fun onFail(errorListener: VolleyError?) {
                        if (refresh_layout != null)
                            refresh_layout.isRefreshing = false
                        Toast.makeText(context, AppLanguage.getString(err_server_connection_error), Toast.LENGTH_LONG).show()
                    }
                })
    }

    private fun getHotDeals() {
        val inputMap = InputMap()
        inputMap[ATTR_SYSTEM_PASSCODE] = SYSTEM_PASSCODE
        inputMap[ATTR_LANGUAGE] = User.getUserLanguageId(context!!)!!.toString()

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

        VolleyRequest.getInstance().post(REQUEST_TODAY_HOT_DEALS, inputMap, object : IVolleyRequest {
            override fun onSuccess(response: JSONObject?) {
                if (refresh_layout != null)
                    refresh_layout.isRefreshing = false
                when (response!!.getInt(ATTR_ERROR_CODE)) {
                    CODE_OK -> {

                        val hotDealsList = ArrayList<HotDeals>()

                        val data = response.getJSONObject(ATTR_DATA).getJSONArray(ATTR_DATA)

                        for (i in 0 until if (data.length() > 3) 3 else data.length()) {
                            hotDealsList.add(HotDeals(data.getJSONObject(i).getInt("ID"),
                                    data.getJSONObject(i).getString("Content"),
                                    data.getJSONObject(i).getString("ImageURL")))
                        }

                        val homeHotDealsAdapter = HomeHotDealsAdapter(hotDealsList, context, HomeHotDealsAdapter.IHomeHotDealsAdapter {
                            launchProductDetails(context!!, it.id.toString())
                        })

                        if (!isVisible) return

                        hot_deals_rv.layoutManager = LinearLayoutManager(activity)
                        hot_deals_rv.setHasFixedSize(true)
                        hot_deals_rv.adapter = homeHotDealsAdapter
                    }
                }
            }

            override fun onFail(errorListener: VolleyError?) {
                if (refresh_layout != null)
                    refresh_layout.isRefreshing = false
                noData(hot_deals_rv, AppLanguage.getString(prompt_please_retry))
                Toast.makeText(context, AppLanguage.getString(err_server_connection_error), Toast.LENGTH_LONG).show()
            }
        })
    }

    private fun getBestSeller() {
        if (!isNetworkAvailable(context!!)) Toast.makeText(context, AppLanguage.getString(err_no_internet_connection), Toast.LENGTH_LONG).show()

        VolleyRequest.getInstance().post(REQUEST_BEST_SELLER, InputMap().apply {
            put(ATTR_SYSTEM_PASSCODE, SYSTEM_PASSCODE)
            put(ATTR_CUSTOMER, User.instance?.id.toString())
            put(ATTR_LANGUAGE, User.getUserLanguageId(context!!)!!.toString())
        }, object : IVolleyRequest {
            override fun onFail(errorListener: VolleyError?) {
                if (refresh_layout != null)
                    refresh_layout.isRefreshing = false
                Toast.makeText(context, AppLanguage.getString(err_server_connection_error), Toast.LENGTH_LONG).show()
            }

            override fun onSuccess(response: JSONObject?) {
                if (refresh_layout != null)
                    refresh_layout.isRefreshing = false
                when (response!!.getInt(ATTR_ERROR_CODE)) {
                    CODE_OK -> {

                        val bestSellerList = ArrayList<BestSeller>()
                        val jsonArray: JSONArray = (response.getJSONObject(ATTR_DATA).getJSONArray(ATTR_DATA))

                        var bestSellerMain: BestSeller? = null

                        for (i in 0 until jsonArray.length()) {
                            val jsonObject = jsonArray.getJSONObject(i).getJSONArray("Product").getJSONObject(0)

                            if (i == 0) {
                                bestSellerMain = BestSeller(jsonObject.getInt("ProductID"), jsonObject.getString("BrandName"), jsonObject.getJSONArray("Images").getString(0))
                            } else {
                                val bestSellerChild = BestSeller(jsonObject.getInt("ProductID"), jsonObject.getString("BrandName"), jsonObject.getJSONArray("Images").getString(0))
                                bestSellerList.add(bestSellerChild)
                            }
                        }

                        if (!isVisible) return

                        recyclerViewBest_seller.layoutManager = GridLayoutManager(context, 2, LinearLayoutManager.HORIZONTAL, false)
                        recyclerViewBest_seller.setHasFixedSize(true)
                        recyclerViewBest_seller.adapter = BestSellerAdapter(context, bestSellerList) { id -> launchProductDetails(context!!, id.toString()) }

                        best_seller_name.text = bestSellerMain?.brandName
                        PicassoUtils.getImage(bestSellerMain!!.images, context!!, best_seller_image, true)

                        best_seller_image.setOnClickListener { launchProductDetails(context!!, bestSellerMain.productId.toString()) }
                    }
                }
            }
        })
    }

    private fun getTodayTrending() {
        if (!isNetworkAvailable(context!!)) Toast.makeText(context, AppLanguage.getString(err_no_internet_connection), Toast.LENGTH_LONG).show()

        VolleyRequest.getInstance().post(REQUEST_TODAY_TRENDING, InputMap().apply {
            put(ATTR_SYSTEM_PASSCODE, SYSTEM_PASSCODE)
            put(ATTR_CUSTOMER, User.instance?.id.toString())
            put(ATTR_LANGUAGE, User.getUserLanguageId(context!!)!!.toString())
        }, object : IVolleyRequest {
            override fun onFail(errorListener: VolleyError?) {
                if (refresh_layout != null)
                    refresh_layout.isRefreshing = false
                Toast.makeText(context, AppLanguage.getString(err_server_connection_error), Toast.LENGTH_LONG).show()
            }

            override fun onSuccess(response: JSONObject?) {
                if (refresh_layout != null)
                    refresh_layout.isRefreshing = false
                when (response!!.getInt(ATTR_ERROR_CODE)) {
                    CODE_OK -> {

                        val todayTrendingList = ArrayList<TodayTrending>()
                        val jsonArray: JSONArray = (response.getJSONObject(ATTR_DATA).getJSONArray(ATTR_DATA))

                        for (i in 0 until jsonArray.length()) {

                            val jsonObject = jsonArray.getJSONObject(i)

                            val todayTrending = TodayTrending(jsonObject.getInt("ID"),
                                    jsonObject.getString("Name"), jsonObject.getString("BrandName"),
                                    jsonObject.getJSONArray("Images").getJSONObject(0).getString("ImageURL")
                                    , jsonObject.getBoolean("IsLiked"))

                            todayTrendingList.add(todayTrending)
                        }

                        if (!isVisible) return

                        todays_terndings_rv.layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
                        todays_terndings_rv.setHasFixedSize(true)
                        todays_terndings_rv.adapter = TodayTrendingAdapter(todayTrendingList, context!!, object : TodayTrendingAdapter.ITodayTrendingAdapter {
                            override fun onClickTodayTrending(todayTrending: TodayTrending) {
                                launchProductDetails(context!!, todayTrending.productID.toString())
                            }
                        })
                    }
                }
            }
        })
    }

    private fun getNewArrival() {
        if (!isNetworkAvailable(context!!)) Toast.makeText(context, AppLanguage.getString(err_no_internet_connection), Toast.LENGTH_LONG).show()

        VolleyRequest.getInstance().post(REQUEST_NEW_ARRIVALS, InputMap().apply {
            put(ATTR_SYSTEM_PASSCODE, SYSTEM_PASSCODE)
            put(ATTR_CURRENCY, User.loadVisibleCurrency(context!!)?.id.toString())
            put(ATTR_LANGUAGE, User.getUserLanguageId(context!!)!!.toString())
        }, object : IVolleyRequest {
            override fun onFail(errorListener: VolleyError?) {
                if (refresh_layout != null)
                    refresh_layout.isRefreshing = false
                Toast.makeText(context, AppLanguage.getString(err_server_connection_error), Toast.LENGTH_LONG).show()
            }

            override fun onSuccess(response: JSONObject?) {
                if (refresh_layout != null)
                    refresh_layout.isRefreshing = false
                when (response!!.getInt(ATTR_ERROR_CODE)) {
                    CODE_OK -> {

                        val newArrivalsList = ArrayList<NewArrivals>()
                        val jsonArray: JSONArray = (response.getJSONObject(ATTR_DATA).getJSONArray(ATTR_DATA))

                        for (i in 0 until jsonArray.length()) {

                            val newArrivals = NewArrivals(jsonArray.getJSONObject(i).getInt("ID"),
                                    jsonArray.getJSONObject(i).getString("Name"),
                                    jsonArray.getJSONObject(i).getInt("Price"),
                                    jsonArray.getJSONObject(i).getString("Symbol"),
                                    jsonArray.getJSONObject(i).getJSONArray("Image").getString(0))

                            newArrivalsList.add(newArrivals)
                        }

                        if (!isVisible) return

                        new_arrival_rv.layoutManager = GridLayoutManager(context, 2)
                        new_arrival_rv.setHasFixedSize(true)
                        new_arrival_rv.adapter = NewArrivalAdapter(newArrivalsList, (activity as AppCompatActivity?)!!, object : NewArrivalAdapter.INewArrivalAdapter {
                            override fun onClickNewArrival(newArrivals: NewArrivals) {
                                launchProductDetails(context!!, newArrivals.id.toString())
                            }
                        })
                    }
                }
            }
        })
    }

    override fun onBackPressed(): Boolean {
        return false
    }

    override fun crucialRequests() {
        Handler(Looper.getMainLooper()).post { getSliderImages() }
        Handler(Looper.getMainLooper()).post { getHotDeals() }
        Handler(Looper.getMainLooper()).post { getBestSeller() }
        Handler(Looper.getMainLooper()).post { getTodayTrending() }
        Handler(Looper.getMainLooper()).post { getNewArrival() }
    }

    private fun scrollSlider(position: Int) {
        val handler = Handler()
        handler.postDelayed({
            activity?.runOnUiThread {
                if (position + 1 >= sliderImages.size) {
                    scrollSlider(0)
                } else {
                    scrollSlider(position + 1)
                }
                slider_images_rv.smoothScrollToPosition(position)
            }
        }, 2500)
    }


}