package com.autotech.we1l.fragments

import android.content.Context
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v7.widget.AppCompatButton
import android.support.v7.widget.AppCompatTextView
import android.support.v7.widget.RecyclerView
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.VolleyError
import com.autotech.we1l.R
import com.autotech.we1l.adapters.PromotionsAdapter
import com.autotech.we1l.app.AppLanguage
import com.autotech.we1l.app.User
import com.autotech.we1l.helpers.InputMap
import com.autotech.we1l.items.Promotion
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.btn_share
import com.autotech.we1l.tools.Language.dialog_opt_no
import com.autotech.we1l.tools.Language.dialog_opt_yes
import com.autotech.we1l.tools.Language.dialog_take_promotion
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.tools.Language.toast_done
import com.autotech.we1l.volley.IVolleyRequest
import com.autotech.we1l.volley.VolleyRequest
import kotlinx.android.synthetic.main.fragment_promotions.*
import org.json.JSONObject
import pub.devrel.easypermissions.EasyPermissions

class PromotionsFragment : BaseFragment(), IOnBackPressedListener {

    // Lists:
    private val promotions = BaseList<Promotion>()

    // Adapters:
    private lateinit var promotionsAdapter: PromotionsAdapter

    // Vars:
    private lateinit var sharedImageUrl: String


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

    override fun setupViews() {
        promotionsAdapter = PromotionsAdapter(context!!, promotions, object : BaseAdapter.OnClickListener<Promotion> {
            override fun onClick(holder: RecyclerView.ViewHolder, position: Int, promotion: Promotion) {
                sharedImageUrl = promotion.imageURL
                if (User.isValid()) {
                    MaterialDialog.Builder(context!!)
                            .contentColor(ContextCompat.getColor(context!!, R.color.black_50))
                            .content(AppLanguage.getString(dialog_take_promotion))
                            .positiveText(AppLanguage.getString(dialog_opt_yes))
                            .onPositive { _, _ ->
                                VolleyRequest.getInstance()
                                        .post(REQUEST_TAKE_PROMOTION, InputMap().apply {
                                            put(ATTR_SYSTEM_PASSCODE, SYSTEM_PASSCODE)
                                            put(ATTR_CUSTOMER, User.instance!!.id.toString())
                                            put(ATTR_PROMOTION, promotion.id.toString())

                                        }, object : IVolleyRequest {

                                            override fun onSuccess(response: JSONObject?) {
                                                when (response!!.getInt(ATTR_ERROR_CODE)) {
                                                    CODE_OK -> {
                                                        Toast.makeText(context, AppLanguage.getString(toast_done), Toast.LENGTH_LONG).show()
                                                    }
                                                }
                                            }

                                            override fun onFail(errorListener: VolleyError?) {
                                                Toast.makeText(context, AppLanguage.getString(err_server_connection_error),
                                                        Toast.LENGTH_LONG).show()
                                            }
                                        }).apply { requestsArray.add(this) }
                            }
                            .negativeText(AppLanguage.getString(dialog_opt_no))
                            .neutralText(AppLanguage.getString(btn_share))
                            .onNeutral { _, _ ->
                                ShareFileUtil.shareFile(this@PromotionsFragment, promotion.imageURL, promotion.name!!, promotion.id.toString())
                            }
                            .show()
                } else {
                    val view = LayoutInflater.from(context).inflate(R.layout.include_not_logged_in, null, false)

                    view.findViewById<AppCompatTextView>(R.id.not_logged_in).text = AppLanguage.getString(Language.prompt_not_logged_in)
                    view.findViewById<AppCompatButton>(R.id.sign_in_or_sign_up).text = AppLanguage.getString(Language.btn_sign_in_or_sign_up)

                    view.findViewById<AppCompatButton>(R.id.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(context!!)
                    }
                    MaterialDialog.Builder(context!!)
                            .customView(view, false)
                            .neutralText(AppLanguage.getString(btn_share))
                            .onNeutral { _, _ ->
                                ShareFileUtil.shareFile(this@PromotionsFragment, promotion.imageURL, promotion.name!!, promotion.id.toString())
                            }
                            .show()
                }

            }
        })

        Tools.setupRV(promotions_rv, promotionsAdapter)
    }

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

    override fun onBackPressed(): Boolean {
        return false
    }

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

        loading(promotions_rv)

        VolleyRequest.getInstance()
                .post(REQUEST_PROMOTIONS, InputMap().apply {
                    put(ATTR_SYSTEM_PASSCODE, SYSTEM_PASSCODE)
                    put(ATTR_LANGUAGE, User.getUserLanguageId(context!!)!!.toString())
                }, object : IVolleyRequest {

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

                                if (promotions.isEmpty()) noData(promotions_rv) else showData(promotions_rv)

                                promotionsAdapter.updateData(promotions)
                            }
                        }
                    }

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

    override fun crucialRequests() {
        getPromotions()
    }

}