package net.pokeranalytics.android.ui.activity

import android.app.KeyguardManager
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.appcompat.app.AlertDialog
import com.google.android.material.bottomnavigation.BottomNavigationView
import io.realm.RealmResults
import kotlinx.android.synthetic.main.activity_home.*
import net.pokeranalytics.android.BuildConfig
import net.pokeranalytics.android.R
import net.pokeranalytics.android.model.realm.Currency
import net.pokeranalytics.android.ui.activity.FiltersActivity
import net.pokeranalytics.android.ui.activity.components.PokerAnalyticsActivity
import net.pokeranalytics.android.ui.adapter.HomePagerAdapter
import timber.log.Timber


class HomeActivity : PokerAnalyticsActivity() {

	companion object {
		fun newInstance(context: Context, id: Int) {
			val intent = Intent(context, HomeActivity::class.java)
			intent.putExtra("id", id)
			context.startActivity(intent)
		}
	}

	private var homeMenu: Menu? = null

	private lateinit var currencies: RealmResults<Currency>

	private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
		when (item.itemId) {
			//CLEAN
			/*
			R.id.navigation_history -> {
				displayFragment(0)
			}
			R.id.navigation_stats -> {
				displayFragment(1)
			}
			R.id.navigation_settings -> {
				displayFragment(2)
			}
			*/
			R.id.navigation_history -> {
				displayFragment(0)
			}
			R.id.navigation_stats -> {
				displayFragment(1)
			}
			R.id.navigation_calendar -> {
				displayFragment(2)
			}
			R.id.navigation_reports -> {
				displayFragment(3)
			}
			R.id.navigation_more -> {
				displayFragment(4)
			}
		}
		return@OnNavigationItemSelectedListener true
	}

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

		if (BuildConfig.DEBUG) {
			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
				setShowWhenLocked(true)
				setTurnScreenOn(true)
				val keyguardManager = getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager
				keyguardManager.requestDismissKeyguard(this, null)
			}
		}

		setContentView(R.layout.activity_home)

		observeRealmObjects()
		initUI()
		checkFirstLaunch()
	}

	override fun onCreateOptionsMenu(menu: Menu?): Boolean {
		menu?.clear()
		menuInflater.inflate(R.menu.toolbar_home, menu)
		this.homeMenu = menu
		//TODO: Change queryWith button visibility
		homeMenu?.findItem(R.id.filter)?.isVisible = true
		return super.onCreateOptionsMenu(menu)
	}

	override fun onOptionsItemSelected(item: MenuItem?): Boolean {
		when (item?.itemId) {
			R.id.filter -> manageFilters()
		}
		return super.onOptionsItemSelected(item)
	}

	private fun observeRealmObjects() {

		val realm = getRealm()

		// observe currency changes
		this.currencies = realm.where(Currency::class.java).findAll()
		this.currencies.addChangeListener { t, _ ->

			realm.beginTransaction()
			t.forEach {
				it.refreshRelatedRatedValues()
			}
			realm.commitTransaction()
		}

	}

	/**
	 * Init UI
	 */
	private fun initUI() {

		setSupportActionBar(toolbar)

		navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)
		navigation.selectedItemId = R.id.navigation_history

		val homePagerAdapter = HomePagerAdapter(supportFragmentManager)
		viewPager.offscreenPageLimit = 5
		viewPager.enablePaging = false
		viewPager.adapter = homePagerAdapter

		updateToolbar(0)
	}

	/**
	 * Check first launch
	 */
	private fun checkFirstLaunch() {
//		if (Preferences.getBoolean(Preferences.Keys.FIRST_LAUNCH, this, true)) {
//			Preferences.setBoolean(Preferences.Keys.FIRST_LAUNCH, false, this)
//			val builder = AlertDialog.Builder(this)
//				.setTitle(String.format(getString(R.string.welcome_in_), getString(R.string.app_name)))
//				.setMessage(R.string.popup_message_welcome)
//				.setNegativeButton(R.string.ok, null)
//			builder.show()
//		}
	}

	/**
	 * Display a new fragment
	 */
	private fun displayFragment(index: Int) {
		viewPager.setCurrentItem(index, false)
		updateToolbar(index)
	}

	/**
	 * Update toolbar
	 */
	private fun updateToolbar(index: Int) {
		when (index) {
			//CLEAN
			/*
			0 -> {
				toolbar.title = getString(R.string.feed)
				homeMenu?.findItem(R.id.queryWith)?.isVisible = false
			}
			1 -> {
				toolbar.title = getString(R.string.stats)
				homeMenu?.findItem(R.id.queryWith)?.isVisible = false
			}
			2 -> {
				toolbar.title = getString(R.string.services)
				homeMenu?.findItem(R.id.queryWith)?.isVisible = false
			}
			*/

			0 -> {
				toolbar.title = getString(R.string.feed)
				homeMenu?.findItem(R.id.filter)?.isVisible = true
			}
			1 -> {
				toolbar.title = getString(R.string.stats)
				homeMenu?.findItem(R.id.filter)?.isVisible = true
			}
			2 -> {
				toolbar.title = getString(R.string.calendar)
				homeMenu?.findItem(R.id.filter)?.isVisible = false
			}
			3 -> {
				toolbar.title = getString(R.string.reports)
				homeMenu?.findItem(R.id.filter)?.isVisible = false
			}
			4 -> {
				toolbar.title = getString(R.string.more)
				homeMenu?.findItem(R.id.filter)?.isVisible = false
			}
		}
	}

	/**
	 * Manage filters
	 */
	private fun manageFilters() {

		val filterSelected = false

		val choices = ArrayList<CharSequence>()
		choices.add(getString(R.string.new_str))

		if (filterSelected) {
			choices.add(getString(R.string.modify_current_filter))
			choices.add(getString(R.string.load_from_db))
			choices.add(getString(R.string.remove_filter))
		}

		val builder = AlertDialog.Builder(this)
		builder.setTitle(R.string.filter_selection)
			.setCancelable(true)
			.setItems(choices.toTypedArray()) { _, which ->
				Timber.d("Click on $which")
				when (which) {
					0 -> FiltersActivity.newInstance(this@HomeActivity)
				}
			}
			.setNegativeButton(R.string.cancel) { _, _ ->
				Timber.d("Click on cancel")
			}

		builder.show()
	}

}
