package net.pokeranalytics.android.ui.activity

import android.app.KeyguardManager
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
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.components.PokerAnalyticsActivity
import net.pokeranalytics.android.ui.activity.components.RequestCode
import net.pokeranalytics.android.ui.activity.components.ResultCode
import net.pokeranalytics.android.ui.adapter.HomePagerAdapter
import net.pokeranalytics.android.ui.extensions.showAlertDialog
import net.pokeranalytics.android.util.billing.AppGuard
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 lateinit var currencies: RealmResults<Currency>
	private var homePagerAdapter: HomePagerAdapter? = null

	private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
		when (item.itemId) {
			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 onResume() {
		super.onResume()
		AppGuard.requestPurchasesUpdate()
	}

	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 onNewIntent(intent: Intent?) {
		super.onNewIntent(intent)

		intent?.let {

			when (intent.action) {
				"android.intent.action.VIEW" -> { // import
					val data = it.data
					if (data != null) {
						this.requestImportConfirmation(data)
					} else {
						throw IllegalStateException("URI null on import")
					}
				}
				else -> {
					Timber.d("Intent ${intent.action} unmanaged")
				}
			}
		}

	}

	override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
		super.onActivityResult(requestCode, resultCode, data)

		when (requestCode) {
			RequestCode.IMPORT.value -> {
				if (resultCode == ResultCode.IMPORT_UNRECOGNIZED_FORMAT.value) {
					showAlertDialog(context = this, message = R.string.unknown_import_format_popup_message)
				}
			}
		}
	}

	private fun observeRealmObjects() {

		val realm = getRealm()

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

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

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

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

	/**
	 * 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)
	}

	// Import

	private fun requestImportConfirmation(uri: Uri) {

		showAlertDialog(context = this, title = R.string.import_confirmation, showCancelButton = true, positiveAction = {
			ImportActivity.newInstanceForResult(this, uri)
		})

	}

}
