package com.autotech.we1l.activities

import android.content.Context
import android.content.res.Configuration
import android.os.Bundle
import android.support.design.internal.BottomNavigationItemView
import android.support.design.internal.BottomNavigationMenuView
import android.support.v4.app.Fragment
import android.support.v4.view.GravityCompat
import android.support.v7.app.ActionBarDrawerToggle
import android.util.Log
import android.view.*
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import com.afollestad.materialdialogs.MaterialDialog
import com.android.volley.VolleyError
import com.autotech.we1l.R
import com.autotech.we1l.app.AppLanguage
import com.autotech.we1l.app.User
import com.autotech.we1l.fragments.*
import com.autotech.we1l.helpers.InputMap
import com.autotech.we1l.items.Country
import com.autotech.we1l.items.Currency
import com.autotech.we1l.my_classes.BaseActivity
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.dialog_confirm_log_out
import com.autotech.we1l.tools.Language.dialog_logging_out
import com.autotech.we1l.tools.Language.dialog_opt_no
import com.autotech.we1l.tools.Language.dialog_opt_yes
import com.autotech.we1l.tools.Language.err_server_connection_error
import com.autotech.we1l.volley.IVolleyRequest
import com.autotech.we1l.volley.VolleyRequest
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.content_main.*
import org.json.JSONObject


class MainActivity : BaseActivity() {

    //private var toolbarTitle = ""

    // Vars:
    private var withOutBadge: View? = null
    private var currFragment: Fragment = HomeFragment()
    private var badgeCounter: TextView? = null
    // Adapters:
    //private lateinit var navigationAdapter: NavigationAdapter

    // Views:
    private var header: View? = null

    companion object {
        lateinit var updateCartBadge: UpdateCartBadge

        interface UpdateCartBadge {
            fun update(cartItemsCount: Int)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_main)

        supportFragmentManager.beginTransaction()
                .replace(R.id.fragment_holder, currFragment)
                .commit()

        doAll()

        getCurrencies()
        getLocationInfo()

        nav_view.setNavigationItemSelectedListener { menuItem ->

            menuItem.isChecked = true

            drawer_layout.closeDrawer(Gravity.START)

            when (menuItem.itemId) {
                R.id.nav_home -> setFragment(HomeFragment(), 0)
                R.id.nav_categories -> setFragment(CategoryFragment(), -1)
                R.id.nav_hot_deals -> setFragment(HotDealsFragment(), -1)
                R.id.nav_offers -> setFragment(AdsFragment(), -1)
                R.id.nav_promotions -> setFragment(PromotionsFragment(), -1)
                R.id.nav_favorite -> setFragment(FavoriteFragment(), 1)
                R.id.nav_purchased -> setFragment(UserOrdersFragment(), -1)
                R.id.nav_track_your_orders -> setFragment(TrackOrderFragment(), -1)
                R.id.nav_settings -> setFragment(SettingsFragment(), -1)
                R.id.nav_help_support -> setFragment(ContactUsFragment(), -1)
                R.id.nav_logout -> logOut()
            }

            false
        }

        nav_view.menu.getItem(0).isChecked = true

        bottomNavigationView.setOnNavigationItemSelectedListener { menuItem ->
            menuItem.isChecked = true

            when (menuItem.itemId) {
                R.id.nav_home -> setFragment(HomeFragment(), 0)
                R.id.nav_favorite -> setFragment(FavoriteFragment(), 1)
                // set the pending notifications value
                R.id.nav_cart -> setFragment(CartFragment(), 2)
                R.id.nav_search -> launchSearchActivity(applicationContext)
                R.id.nav_profile -> setFragment(ProfileFragment(), -1)
            }

            false
        }
        //  pendingNotifications = User.cartProducts;
        val bottomNavigationMenuView: BottomNavigationMenuView = bottomNavigationView.getChildAt(0) as BottomNavigationMenuView
        val v: View = bottomNavigationMenuView.getChildAt(2)
        val itemView: BottomNavigationItemView = v as BottomNavigationItemView

        val badge: View = LayoutInflater.from(this).inflate(R.layout.notification_badge, bottomNavigationMenuView, false)
        withOutBadge = itemView.getChildAt(0)

        if (User.cartProducts.isNotEmpty()) {
            itemView.removeAllViews()
            itemView.addView(badge)
            badgeCounter = findViewById(R.id.badge_counter)
            badgeCounter?.text = User.cartProducts.size.toString()
        }

        if (!User.isValid())
            nav_view.menu.findItem(R.id.nav_logout).title = AppLanguage.getString(Language.btn_log_in)


        nav_view.menu.findItem(R.id.nav_home).title = AppLanguage.getString(Language.nav_home)
        nav_view.menu.findItem(R.id.nav_categories).title = AppLanguage.getString(Language.nav_categories)
        nav_view.menu.findItem(R.id.nav_hot_deals).title = AppLanguage.getString(Language.txt_hot_deal)
        nav_view.menu.findItem(R.id.nav_promotions).title = AppLanguage.getString(Language.nav_promotions)
        nav_view.menu.findItem(R.id.nav_offers).title = AppLanguage.getString(Language.nav_ads)
        nav_view.menu.findItem(R.id.nav_favorite).title = AppLanguage.getString(Language.btn_favorites)
        nav_view.menu.findItem(R.id.nav_purchased).title = AppLanguage.getString(Language.txt_purchased)
        nav_view.menu.findItem(R.id.nav_track_your_orders).title = AppLanguage.getString(Language.txt_track_your_rders)
        nav_view.menu.findItem(R.id.nav_settings).title = AppLanguage.getString(Language.nav_settings)
        nav_view.menu.findItem(R.id.nav_help_support).title = AppLanguage.getString(Language.txt_help)
        if (!User.isValid()) nav_view.menu.findItem(R.id.nav_logout).title = AppLanguage.getString(Language.btn_log_in)
        else nav_view.menu.findItem(R.id.nav_logout).title = AppLanguage.getString(Language.btn_log_out)

//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
//            window.decorView.findViewById<ViewGroup>(android.R.id.content).layoutDirection = LAYOUT_DIRECTION_RTL
//        }
    }

    private fun setChecked(index: Int) {

        if (index == -1) return

        var drawableInt = 0
        var indexId = 0

        when (index) {
            0 -> {
                drawableInt = R.drawable.ic_bottom_category_active
                indexId = R.id.nav_home
                nav_view.menu.findItem(R.id.nav_home).isChecked = true
                bottomNavigationView.menu.getItem(0).isChecked = true
            }
            1 -> {
                drawableInt = R.drawable.ic_bottom_favorite_active
                indexId = R.id.nav_favorite
                nav_view.menu.getItem(5).isChecked = true
                bottomNavigationView.menu.getItem(1).isChecked = true
            }
            2 -> {


                if (User.cartProducts.isNotEmpty() && withOutBadge != null)
                    clearBadge()

                drawableInt = R.drawable.ic_bottom_cart_active
                indexId = R.id.nav_cart

            }
            3 -> {
                drawableInt = R.drawable.ic_bottom_search_active
                indexId = 3
                bottomNavigationView.menu.getItem(3).isChecked = true
            }
        }

//        bottomNavigationView.menu.getItem(indexId).setIcon(R.drawable.ic_nav_categories)

    }

    fun clearBadge() {
        val bottomNavigationMenuView: BottomNavigationMenuView =
                bottomNavigationView.getChildAt(0) as BottomNavigationMenuView
        val v: View = bottomNavigationMenuView.getChildAt(2)
        val itemView: BottomNavigationItemView = v as BottomNavigationItemView

        itemView.removeAllViews()
        itemView.addView(withOutBadge)
    }

    override fun onRestart() {
        checkBadge()
        super.onRestart()
    }

    private fun checkBadge() {
        if (User.cartProducts.isNotEmpty()) {
            val bottomNavigationMenuView: BottomNavigationMenuView =
                    bottomNavigationView.getChildAt(0) as BottomNavigationMenuView
            val v: View = bottomNavigationMenuView.getChildAt(2)
            val itemView: BottomNavigationItemView = v as BottomNavigationItemView

            val badge: View = LayoutInflater.from(this)
                    .inflate(R.layout.notification_badge, bottomNavigationMenuView, false)

            // withOutBadge=itemView.getChildAt(0);
            itemView.removeAllViews()

            itemView.addView(badge)
            badgeCounter = findViewById(R.id.badge_counter)
            badgeCounter?.text = User.cartProducts.size.toString()
        }
    }

    fun setFragment(fragment: Fragment, index: Int) {

        if (fragment == currFragment) return

        supportFragmentManager.beginTransaction()
                .replace(R.id.fragment_holder, fragment)
                .commit()

        currFragment = fragment

        setChecked(index)
    }

    override fun onConfigurationChanged(newConfig: Configuration?) {
        super.onConfigurationChanged(newConfig)

        currFragment.onConfigurationChanged(newConfig)
    }

    var menuItem: MenuItem? = null
    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        /*   menuInflater.inflate(R.menu.bottom_menu, menu)
           menuItem = menu.findItem(R.id.nav_cart);
           pendingNotifications=5;

           if(pendingNotifications==0)
           {
               menuItem?.setActionView(null);

           }else{

               runOnUiThread{
                   menuItem?.setActionView(R.layout.notification_badge);

                   badgeCounter = findViewById(R.id.badge_counter);
                   badgeCounter?.setText(pendingNotifications.toString());
               }

           }

   */
//        notificationBadge = menu.findItem(R.id.cart).actionView.findViewById(R.id.cart_badge)
//
//        updateCartBadge = object : UpdateCartBadge {
//            override fun update(cartItemsCount: Int) {
//                runOnUiThread {
//                    if (cartItemsCount == 0) {
//                        notificationBadge.visibility = View.GONE
//                    } else {
//                        notificationBadge.visibility = View.VISIBLE
//                        notificationBadge.text = cartItemsCount.toString()
//                    }
//                }
//            }
//        }
//
//        updateCartBadge.update(User.cartProducts.size)
//
//        menu.findItem(R.id.cart).actionView.setOnClickListener {
//            launchCart(this)
//        }

        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return true
//        return when (item.itemId) {
//            R.id.notifications -> {
//                launchNotifications(this)
//                true
//            }
//            R.id.search -> {
//                launchSearchActivity(this)
//                true
//            }
//            else -> super.onOptionsItemSelected(item)
//        }
    }

    override fun setupLanguages() {

    }

    override fun setupViews() {
        setSupportActionBar(toolbar)

        val toggle = ActionBarDrawerToggle(this, drawer_layout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)

        drawer_layout.addDrawerListener(toggle)

        toggle.syncState()

        header = LayoutInflater.from(this).inflate(R.layout.layout_header, null) as View

        nav_view.addHeaderView(header!!)

        getUserPoints()
    }


    fun getUserPoints() {

        val textViewName = header?.findViewById(R.id.textViewName) as TextView
        val profileImageLayout = header?.findViewById(R.id.profile_image_layout) as ImageView
        val textViewPoints = header?.findViewById(R.id.textViewPoints) as TextView

        if (User.isValid()) {
            textViewName.text = User.instance?.fullName
            PicassoUtils.getImage(User.instance?.imageUrl!!, applicationContext, profileImageLayout)

            VolleyRequest.getInstance()
                    .post(REQUEST_GET_STORE_CREDIT, InputMap().apply {
                        put(ATTR_SYSTEM_PASSCODE, SYSTEM_PASSCODE)
                        put(ATTR_CUSTOMER, User.instance!!.id.toString())
                        put(ATTR_CURRENCY, User.loadVisibleCurrency(applicationContext!!)!!.id.toString())
                    }, object : IVolleyRequest {

                        override fun onSuccess(response: JSONObject?) {
                            when (response!!.getInt(ATTR_ERROR_CODE)) {
                                CODE_OK -> textViewPoints.text = response.getJSONObject("Data").getString("Data") + " " + User.loadVisibleCurrency(applicationContext)?.name
                            }
                        }

                        override fun onFail(errorListener: VolleyError?) {
                        }
                    }).apply { requestsArray.add(this) }
        }
    }

    private fun logOut() {

        if (!User.isValid()) {

            val sharedPreferences = getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE)
            User.cartProducts.clear()
            sharedPreferences.edit().putBoolean(ATTR_IS_UNREGISTERED, false).apply()
            launchFirstActivity(this@MainActivity)
            return
        }

        MaterialDialog.Builder(this)
                .content(AppLanguage.getString(dialog_confirm_log_out))
                .positiveText(AppLanguage.getString(dialog_opt_yes))
                .positiveColor(resources.getColor(R.color.pink))
                .onPositive { _, _ ->

                    val progressDialog = MaterialDialog.Builder(this)
                            .content(AppLanguage.getString(dialog_logging_out))
                            .progress(true, 100)
                            .cancelable(false)
                            .show()

                    val inputMap = HashMap<String, String>()

                    inputMap[ATTR_SYSTEM_PASSCODE] = SYSTEM_PASSCODE
                    inputMap[ATTR_ID] = User.instance?.id.toString()

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

                        override fun onSuccess(response: JSONObject) {
                            runOnUiThread {
                                progressDialog.dismiss()
                            }
                            when (response.getInt(ATTR_ERROR_CODE)) {
                                CODE_OK -> {
                                    User.delete(this@MainActivity)
                                    launchFirstActivity(this@MainActivity)
                                }
                            }
                        }

                        override fun onFail(error: VolleyError) {
                            runOnUiThread {
                                Toast.makeText(this@MainActivity, AppLanguage.getString(err_server_connection_error), Toast.LENGTH_LONG).show()
                                progressDialog.dismiss()
                            }
                        }
                    }).apply { requestsArray.add(this) }
                }
                .negativeText(AppLanguage.getString(dialog_opt_no))
                .show()

    }

    override fun setupClickListeners() {
//        log_out.setOnClickListener {
//            if (User.isValid())
//                MaterialDialog.Builder(this)
//                        .content(AppLanguage.getString(dialog_confirm_log_out))
//                        .positiveText(AppLanguage.getString(dialog_opt_yes))
//                        .positiveColor(resources.getColor(R.color.pink))
//                        .onPositive { _, _ ->
//
//                            val progressDialog = MaterialDialog.Builder(this)
//                                    .content(AppLanguage.getString(dialog_logging_out))
//                                    .progress(true, 100)
//                                    .cancelable(false)
//                                    .show()
//
//                            val inputMap = HashMap<String, String>()
//
//                            inputMap[ATTR_SYSTEM_PASSCODE] = SYSTEM_PASSCODE
//                            inputMap[ATTR_ID] = User.instance?.id.toString()
//
//                            VolleyRequest.getInstance().post(REQUEST_LOG_OUT, inputMap, object : IVolleyRequest {
//
//                                override fun onSuccess(response: JSONObject) {
//                                    runOnUiThread {
//                                        progressDialog.dismiss()
//                                    }
//                                    when (response.getInt(ATTR_ERROR_CODE)) {
//                                        CODE_OK -> {
//                                            User.delete(this@MainActivity)
//                                            launchFirstActivity(this@MainActivity)
//                                        }
//                                    }
//                                }
//
//                                override fun onFail(error: VolleyError) {
//                                    runOnUiThread {
//                                        Toast.makeText(this@MainActivity, AppLanguage.getString(err_server_connection_error), Toast.LENGTH_LONG).show()
//                                        progressDialog.dismiss()
//                                    }
//                                }
//                            }).apply { requestsArray.add(this) }
//                        }
//                        .negativeText(AppLanguage.getString(dialog_opt_no))
//                        .show()
//            else {
//                val sharedPreferences = getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE)
//                User.cartProducts.clear()
//                sharedPreferences.edit().putBoolean(ATTR_IS_UNREGISTERED, false).apply()
//                launchFirstActivity(this@MainActivity)
//            }
//        }
    }


    override fun onBackPressed() {
        when {
            drawer_layout.isDrawerOpen(GravityCompat.START) -> drawer_layout.closeDrawer(GravityCompat.START)

            (currFragment as IOnBackPressedListener).onBackPressed() -> return

            (currFragment !is HomeFragment) -> {
                currFragment = HomeFragment()
                setFragment(HomeFragment(), 0)
            }

            else -> super.onBackPressed()
        }
    }

    private fun getCurrencies() {

        val places = BaseList<Country>()

        val inputMap = HashMap<String, String>()
        inputMap[ATTR_SYSTEM_PASSCODE] = SYSTEM_PASSCODE

        VolleyRequest.getInstance().post(REQUEST_GET_PLACES, inputMap, object : IVolleyRequest {
            override fun onSuccess(response: JSONObject?) {
                when (response!!.getInt(ATTR_ERROR_CODE)) {
                    CODE_OK -> {
                        val data = response.getJSONObject(ATTR_DATA).getJSONArray(ATTR_DATA)
                        for (i in 0 until data.length()) {
                            places.add(Country(data.getJSONObject(i)))
                        }
                    }
                }
            }

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

    private fun getLocationInfo() {
        VolleyRequest.getInstance()
                .post(REQUEST_LOCATION_INFO, InputMap().apply {
                    put(ATTR_SYSTEM_PASSCODE, SYSTEM_PASSCODE)
                }, object : IVolleyRequest {
                    override fun onSuccess(response: JSONObject?) {
                        when (response!!.getInt(ATTR_ERROR_CODE)) {
                            CODE_OK -> {
                                User.saveCurrency(this@MainActivity,
                                        Currency(response.getJSONObject(ATTR_DATA).getInt(ATTR_CURRENCY_ID),
                                                response.getJSONObject(ATTR_DATA).getString(ATTR_sYMBOL),
                                                response.getJSONObject(ATTR_DATA).getString(ATTR_COUNTRY.toLowerCase())))
                            }
                        }
                    }

                    override fun onFail(errorListener: VolleyError?) {

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