package com.autotech.we1l.fragments

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import com.afollestad.materialdialogs.MaterialDialog
import com.android.volley.Response
import com.android.volley.VolleyError
import com.android.volley.toolbox.HurlStack
import com.android.volley.toolbox.Volley
import com.autotech.we1l.R
import com.autotech.we1l.activities.MainActivity
import com.autotech.we1l.app.AppLanguage
import com.autotech.we1l.app.User
import com.autotech.we1l.helpers.InputMap
import com.autotech.we1l.items.Currency
import com.autotech.we1l.items.LanguageItem
import com.autotech.we1l.my_classes.BaseFragment
import com.autotech.we1l.my_classes.BaseList
import com.autotech.we1l.tools.*
import com.autotech.we1l.tools.Language.attr_country
import com.autotech.we1l.tools.Language.attr_currency
import com.autotech.we1l.tools.Language.attr_languages
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.hint_languages
import com.autotech.we1l.volley.IVolleyRequest
import com.autotech.we1l.volley.InputStreamVolleyRequest
import com.autotech.we1l.volley.VolleyRequest
import kotlinx.android.synthetic.main.fragment_settings.*
import org.json.JSONObject
import java.io.File
import java.util.*


class SettingsFragment : BaseFragment() {

    // Lists:
    private val languages = BaseList<LanguageItem>()
    private val currencies = BaseList<Currency>()

    // Vars:
    private var selectedLanguage: LanguageItem? = null

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

    override fun setupViews() {
        //is_local.text = isLocal.toString()
        currency.text = User.loadVisibleCurrency(context!!)?.name ?: ""
        country.text = User.loadCurrency(context!!)?.countryName ?: ""
        textViewTitle.text = AppLanguage.getString(Language.nav_settings).toUpperCase(Locale.getDefault())
    }

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

        languages_spinner.setOnItemSelectedListener { _, position, _, _ ->

            val langFileDir = File(context?.cacheDir?.absolutePath +
                    FOLDER_NAME + SETTINGS_FOLDER_NAME)
            var langFile = File(langFileDir, "${languages[position].symbol}.json")

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

            if (langFile.exists()) {
                langFile.delete()
                langFile = File(langFileDir, "${languages[position].symbol}.json")
            }

            val dialog = MaterialDialog.Builder(context!!)
                    .progress(true, 100)
                    .cancelable(false)
                    .show()

            /////
            val request = InputStreamVolleyRequest(languages[position].url,
                    Response.Listener<ByteArray> {
                        AppLanguage.saveLanguageSettings(context!!, languages[position].symbol)
                        if (it != null) {
                            AppLanguage.saveLanguageFile(context, it)
                            User.saveUserLanguage(context, languages[position].symbol)
                            User.saveUserLanguageId(context, languages[position].id!!)
                        } else
                            AppLanguage.saveLanguageFile(context, null)

                        launchFirstActivity(context!!)
                        dialog.dismiss()
                    },
                    Response.ErrorListener { })
            val mRequestQueue = Volley.newRequestQueue(activity, HurlStack())
            mRequestQueue.add(request)
            /////

//            VolleyRequest.getInstance()
//                    .post(REQUEST_LANGUAGE_FILE, InputMap().apply {
//                        put(ATTR_SYSTEM_PASSCODE, SYSTEM_PASSCODE)
//                        put(ATTR_ID, languages[position].id.toString())
//                    }, object : IVolleyRequest {
//
//                        override fun onSuccess(response: JSONObject?) =
//                                when (response!!.getInt(ATTR_ERROR_CODE)) {
//                                    CODE_OK -> {
//                                        AppLanguage.saveLanguageSettings(context!!, languages[position].symbol)
//                                        val langJSON = response.getJSONObject(ATTR_DATA).getString(ATTR_DATA)
//                                        if (langJSON != "null") {
//                                            AppLanguage.saveLanguageFile(context, JSONObject(langJSON))
//                                            User.saveUserLanguage(context, languages[position].symbol)
//                                        } else
//                                            AppLanguage.saveLanguageFile(context, JSONObject())
//                                        launchFirstActivity(context!!)
//                                        dialog.dismiss()
//                                    }
//                                    else -> {
//                                        dialog.dismiss()
//                                    }
//                                }
//
//                        override fun onFail(errorListener: VolleyError?) {
//                            Toast.makeText(context, AppLanguage.getString(err_server_connection_error), Toast.LENGTH_LONG).show()
//                            dialog.dismiss()
//                        }
//                    }).apply { requestsArray.add(this) }
        }

        currencies_spinner.setOnItemSelectedListener { _, position, _, _ ->
            User.saveVisibleCurrency(context!!, currencies[position])
            currency.text = User.loadVisibleCurrency(context!!)?.name ?: ""
            (activity as MainActivity).getUserPoints()
        }

    }

    override fun setupLanguages() {
        super.setupLanguages()
        language_title.text = AppLanguage.getString(attr_languages)

        languages_spinner.hint = AppLanguage.getString(hint_languages)
        currency_label.text = AppLanguage.getString(attr_currency)
        country_label.text = AppLanguage.getString(attr_country)
        currency_title.text = AppLanguage.getString(attr_currency)
    }

    override fun onResume() {
        super.onResume()
        setupViews()
    }

    private fun getLanguages() {
        VolleyRequest.getInstance()
                .post(REQUEST_GET_LANGUAGES, InputMap().apply {
                    put(ATTR_SYSTEM_PASSCODE, SYSTEM_PASSCODE)
                    put(ATTR_TYPE, 0.toString())
                }, object : IVolleyRequest {

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

                    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()
                    }
                }).apply { requestsArray.add(this) }
    }

    private fun getCurrencies() {

        VolleyRequest.getInstance().post(REQUEST_GET_CURRENCIES, InputMap().apply {
            put(ATTR_SYSTEM_PASSCODE, SYSTEM_PASSCODE)
        }, object : IVolleyRequest {

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

                        val data = response.getJSONObject(ATTR_DATA).getJSONArray(ATTR_DATA)
                        for (i in 0 until data.length()) {
                            currencies.add(Currency(data.getJSONObject(i)))
                        }

                        currencies_spinner.setItems(currencies.names)
                        val currVisibleCurrency = User.loadVisibleCurrency(context!!)
                        if (currVisibleCurrency != null)
                            currencies.forEachIndexed { index, currency ->
                                if (currVisibleCurrency.id == currency.id) {
                                    currencies_spinner.selectedIndex = index
                                }
                            }
                        else
                            User.saveVisibleCurrency(context!!, currencies[0])
                    }
                }
            }

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

    }

    override fun crucialRequests() {
        getLanguages()
        getCurrencies()
    }

    private fun setupLanguagesSpinner() {
        languages_spinner.setItems(languages.names)
        languages.forEachIndexed { index, languageItem ->
            if (languageItem.symbol == AppLanguage.language) {
                languages_spinner.selectedIndex = index
            }
        }
    }
}