package com.autotech.we1l.fragments

import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
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.activities.MainActivity
import com.autotech.we1l.adapters.MainCategoriesAdapter
import com.autotech.we1l.app.AppLanguage
import com.autotech.we1l.app.User
import com.autotech.we1l.helpers.AnimatorUtils
import com.autotech.we1l.items.Category
import com.autotech.we1l.items.ParentCategory
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.err_server_connection_error
import com.autotech.we1l.tools.Language.prompt_please_retry
import com.autotech.we1l.volley.IVolleyRequest
import com.autotech.we1l.volley.VolleyRequest
import kotlinx.android.synthetic.main.fragment_category.*
import kotlinx.android.synthetic.main.fragment_category.refresh_layout
import kotlinx.android.synthetic.main.fragment_category.textViewTitle
import kotlinx.android.synthetic.main.fragment_settings.*
import kotlinx.android.synthetic.main.include_loading_no_data.*
import org.json.JSONObject
import java.util.*
import kotlin.collections.HashMap

class CategoryFragment : BaseFragment(), IOnBackPressedListener {

    private var parentCategoryList = BaseList<ParentCategory>()

    override fun onPause() {
        super.onPause()

        parentCategoryList.clear()
    }

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

    override fun setupViews() {
        parentCategoryList.clear()
        textViewTitle.text = AppLanguage.getString(Language.nav_categories).toUpperCase(Locale.getDefault())
    }

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

    override fun setupLanguages() {
        super.setupLanguages()

        no_data_text.text = com.autotech.we1l.app.AppLanguage.getString(Language.txt_v_no_data)
        loading_text.text = com.autotech.we1l.app.AppLanguage.getString(Language.dialog_loading)
    }

    override fun crucialRequests() {
        getCategories()
    }

    private fun setupCategories() {
        AnimatorUtils.hideThenShow(full_layout) {

            if (parentCategoryList.isEmpty()) {
                noData(main_layout)
            } else {
                showData(main_layout)
            }

            categories_rv.layoutManager = LinearLayoutManager(context)
            categories_rv.setHasFixedSize(true)
            categories_rv.adapter = MainCategoriesAdapter(parentCategoryList, context) { id ->
                run {
                    val subCategoriesFragment = SubCategoriesFragment()
                    val bundle = Bundle()
                    bundle.putString("CATEGORY_ID", id)
                    subCategoriesFragment.arguments = bundle
                    (activity as MainActivity).setFragment(subCategoriesFragment, -1)
                }
            }
        }
    }

    override fun onBackPressed(): Boolean {
        return false
    }

    private fun getCategories() {
        val inputMap = HashMap<String, String>()
        inputMap[ATTR_SYSTEM_PASSCODE] = SYSTEM_PASSCODE
        inputMap[ATTR_LANGUAGE] = User.getUserLanguageId(context!!)!!.toString()
        if (!isNetworkAvailable(context!!)) {
            Toast.makeText(context, com.autotech.we1l.app.AppLanguage.getString(err_no_internet_connection), Toast.LENGTH_LONG).show()
            return
        }

        loading(main_layout)

        VolleyRequest.getInstance().post(REQUEST_GET_CATEGORIES, 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 data = response.getJSONObject(ATTR_DATA).getJSONArray(ATTR_DATA)

                        for (i in 0 until data.length()) {
                            if (data.getJSONObject(i).getInt(ATTR_P_CAT_ID) == -1)
                                parentCategoryList.add(ParentCategory(data.getJSONObject(i).getInt(ATTR_ID),
                                        data.getJSONObject(i).getString(ATTR_NAME),
                                        BaseList()))
                        }

                        for (i in 0 until parentCategoryList.size) {
                            for (j in 0 until data.length())
                                if (parentCategoryList[i].id == data.getJSONObject(j).getInt(ATTR_P_CAT_ID))
                                    parentCategoryList[i].categoryList?.add(Category(data.getJSONObject(j)))
                        }

                        if (parentCategoryList.isEmpty()) {
                            noData(main_layout)
                        } else {
                            showData(main_layout)
                        }

                        setupCategories()
                    }
                }
            }

            override fun onFail(error: VolleyError) {
                if (refresh_layout != null)
                    refresh_layout.isRefreshing = false
                noData(main_layout, com.autotech.we1l.app.AppLanguage.getString(prompt_please_retry))
                Toast.makeText(context, com.autotech.we1l.app.AppLanguage.getString(err_server_connection_error), Toast.LENGTH_LONG).show()

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

}
