package net.pokeranalytics.android.ui.fragment

import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import io.realm.Realm
import kotlinx.android.synthetic.main.fragment_settings.*
import net.pokeranalytics.android.BuildConfig
import net.pokeranalytics.android.R
import net.pokeranalytics.android.model.realm.Session
import net.pokeranalytics.android.ui.activity.BillingActivity
import net.pokeranalytics.android.ui.activity.CurrenciesActivity
import net.pokeranalytics.android.ui.activity.DataListActivity
import net.pokeranalytics.android.ui.activity.GDPRActivity
import net.pokeranalytics.android.ui.adapter.RowRepresentableAdapter
import net.pokeranalytics.android.ui.adapter.RowRepresentableDelegate
import net.pokeranalytics.android.ui.adapter.StaticRowRepresentableDataSource
import net.pokeranalytics.android.ui.extensions.openContactMail
import net.pokeranalytics.android.ui.extensions.openPlayStorePage
import net.pokeranalytics.android.ui.extensions.openUrl
import net.pokeranalytics.android.ui.fragment.components.PokerAnalyticsFragment
import net.pokeranalytics.android.ui.view.RowRepresentable
import net.pokeranalytics.android.ui.view.rowrepresentable.SettingRow
import net.pokeranalytics.android.util.Preferences
import net.pokeranalytics.android.util.URL
import net.pokeranalytics.android.util.UserDefaults
import net.pokeranalytics.android.util.billing.AppGuard
import net.pokeranalytics.android.util.billing.IAPProducts
import timber.log.Timber
import java.util.*


class SettingsFragment : PokerAnalyticsFragment(), RowRepresentableDelegate, StaticRowRepresentableDataSource {


	companion object {

		/**
		 * Create new instance
		 */
		fun newInstance(): SettingsFragment {
			val fragment = SettingsFragment()
			val bundle = Bundle()
			fragment.arguments = bundle
			return fragment
		}

		val rowRepresentation: List<RowRepresentable> by lazy {
			val rows = ArrayList<RowRepresentable>()
			rows.addAll(SettingRow.getRows())
			rows
		}

		const val REQUEST_CODE_CURRENCY: Int = 100
	}

	private lateinit var settingsAdapterRow: RowRepresentableAdapter

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

	override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
		super.onViewCreated(view, savedInstanceState)
		initData()
		initUI()
	}

	override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
		if (requestCode == REQUEST_CODE_CURRENCY && resultCode == Activity.RESULT_OK) {
			data?.let {
				Preferences.setCurrencyCode(data.getStringExtra(CurrenciesFragment.INTENT_CURRENCY_CODE), requireContext())
                val realm = Realm.getDefaultInstance()
                realm.executeTransaction {
                    it.where(Session::class.java).isNull("bankroll.currency.code").findAll().forEach {
                        it.bankrollHasBeenUpdated()
                    }
                }
                realm.close()
				settingsAdapterRow.refreshRow(SettingRow.CURRENCY)
			}
		}
	}

	override fun adapterRows(): List<RowRepresentable>? {
		return rowRepresentation
	}

	override fun stringForRow(row: RowRepresentable): String {
		return when (row) {
			SettingRow.SUBSCRIPTION -> AppGuard.subscriptionStatus(requireContext())
			SettingRow.VERSION -> BuildConfig.VERSION_NAME + if (BuildConfig.DEBUG) " (${BuildConfig.VERSION_CODE}) DEBUG" else ""
			SettingRow.CURRENCY -> UserDefaults.currency.symbol
			else -> ""
		}
	}

	override fun onRowSelected(position: Int, row: RowRepresentable, fromAction: Boolean) {
		when (row) {
			SettingRow.SUBSCRIPTION -> {
				if (!AppGuard.isProUser) {
					BillingActivity.newInstance(requireContext())
				} else {
					this.openPlaystoreAccount()
				}
			}
			SettingRow.RATE_APP -> parentActivity?.openPlayStorePage()
			SettingRow.CONTACT_US -> parentActivity?.openContactMail(R.string.contact)
			SettingRow.BUG_REPORT -> parentActivity?.openContactMail(R.string.bug_report_subject, Realm.getDefaultInstance().path)
			SettingRow.CURRENCY -> CurrenciesActivity.newInstanceForResult(this@SettingsFragment, REQUEST_CODE_CURRENCY)
			SettingRow.FOLLOW_US -> {
				when (position) {
					0 -> parentActivity?.openUrl(URL.BLOG.value)
					1 -> parentActivity?.openUrl(URL.INSTAGRAM.value)
					2 -> parentActivity?.openUrl(URL.TWITTER.value)
					3 -> parentActivity?.openUrl(URL.FACEBOOK.value)
				}
			}
			SettingRow.PRIVACY_POLICY -> parentActivity?.openUrl(URL.PRIVACY_POLICY.value)
			SettingRow.TERMS_OF_USE -> parentActivity?.openUrl(URL.TERMS.value)
			SettingRow.GDPR -> openGDPRActivity()
		}

		row.relatedResultsRepresentable?.let {
			DataListActivity.newInstance(requireContext(), it.ordinal)
		}
	}

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

		setDisplayHomeAsUpEnabled(true)

		val viewManager = LinearLayoutManager(requireContext())
		settingsAdapterRow = RowRepresentableAdapter(
			this, this
		)

		recyclerView.apply {
			setHasFixedSize(true)
			layoutManager = viewManager
			adapter = settingsAdapterRow
		}
	}

	/**
	 * Init data
	 */
	private fun initData() {

	}

	/**
	 * Open GDPR Activity
	 */
	private fun openGDPRActivity() {
		val intent = Intent(requireContext(), GDPRActivity::class.java)
		startActivity(intent)
	}

	/**
	 * Open Google Play account
	 */
	private fun openPlaystoreAccount() {

		val packageName = "net.pokeranalytics.android"
		val sku = IAPProducts.PRO.identifier

		try {
			startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/account/subscriptions?sku=$sku&package=$packageName")))
		} catch (e: ActivityNotFoundException) {
			Timber.d(e)
		}
	}

}