package net.pokeranalytics.android.ui.extensions

import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.content.res.Resources
import android.net.Uri
import android.util.TypedValue
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.widget.AppCompatTextView
import androidx.browser.customtabs.CustomTabsIntent
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import androidx.core.view.isVisible
import net.pokeranalytics.android.BuildConfig
import net.pokeranalytics.android.R
import net.pokeranalytics.android.ui.activity.components.PokerAnalyticsActivity
import net.pokeranalytics.android.ui.fragment.components.PokerAnalyticsFragment
import net.pokeranalytics.android.util.DeviceUtils
import net.pokeranalytics.android.util.TextFormat
import net.pokeranalytics.android.util.URL
import net.pokeranalytics.android.util.billing.AppGuard
import java.io.File


// Sizes
val Int.dp: Int
	get() = (this / Resources.getSystem().displayMetrics.density).toInt()
val Int.px: Int
	get() = (this * Resources.getSystem().displayMetrics.density).toInt()
val Float.dp: Float
	get() = (this / Resources.getSystem().displayMetrics.density)
val Float.px: Float
	get() = (this * Resources.getSystem().displayMetrics.density)


// Toast
fun PokerAnalyticsActivity.toast(message: String) {
	Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}

fun PokerAnalyticsFragment.toast(message: String) {
	Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show()
}

// Open Play Store for rating
fun PokerAnalyticsActivity.openPlayStorePage() {
	val uri = Uri.parse("market://details?id=$packageName")
	val goToMarket = Intent(Intent.ACTION_VIEW, uri)
	goToMarket.addFlags(
		Intent.FLAG_ACTIVITY_NO_HISTORY or Intent.FLAG_ACTIVITY_NEW_DOCUMENT or
				Intent.FLAG_ACTIVITY_MULTIPLE_TASK
	)
	try {
		startActivity(goToMarket)
	} catch (e: ActivityNotFoundException) {
		startActivity(
			Intent(
				Intent.ACTION_VIEW, Uri.parse(
					"http://play.google.com/store/apps/details?id=$packageName"
				)
			)
		)
	}
}

// Open email for "Contact us"
fun PokerAnalyticsActivity.openContactMail(subjectStringRes: Int, filePath: String? = null) {
	val info =
		"v${BuildConfig.VERSION_NAME}(${BuildConfig.VERSION_CODE}) - ${AppGuard.isProUser}, Android ${android.os.Build.VERSION.SDK_INT}, ${DeviceUtils.getDeviceName()}"

	val emailIntent = Intent(Intent.ACTION_SEND)

	filePath?.let {
		val databaseFile = File(it)
		val contentUri = FileProvider.getUriForFile(this, "net.pokeranalytics.android.fileprovider", databaseFile)
		if (contentUri != null) {
			emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
			emailIntent.setDataAndType(contentUri, contentResolver.getType(contentUri))
			emailIntent.putExtra(Intent.EXTRA_STREAM, contentUri)
		}
	}

	emailIntent.type = "message/rfc822"
	emailIntent.putExtra(Intent.EXTRA_SUBJECT, getString(subjectStringRes))
	emailIntent.putExtra(Intent.EXTRA_TEXT, "\n\n$info")
	emailIntent.putExtra(Intent.EXTRA_EMAIL, arrayOf(URL.SUPPORT_EMAIL.value))

	startActivity(Intent.createChooser(emailIntent, getString(R.string.contact)))
}

// Open custom tab
fun PokerAnalyticsActivity.openUrl(url: String) {
	val builder: CustomTabsIntent.Builder = CustomTabsIntent.Builder()
	builder.setToolbarColor(ContextCompat.getColor(this, net.pokeranalytics.android.R.color.colorPrimary))
	val customTabsIntent = builder.build()
	customTabsIntent.launchUrl(this, Uri.parse(url))
}

// Display Alert Dialog
fun PokerAnalyticsActivity.showAlertDialog(title: Int? = null, message: Int? = null) {
	showAlertDialog(this, title, message)
}

fun PokerAnalyticsFragment.showAlertDialog(title: Int? = null, message: Int? = null) {
	context?.let {
		showAlertDialog(it, title, message)
	}
}

/**
 * Create and show an alert dialog
 */
fun showAlertDialog(
	context: Context, title: Int? = null, message: Int? = null, cancelButtonTitle: Int? = null, showCancelButton: Boolean = false,
	positiveAction: (() -> Unit)? = null, negativeAction: (() -> Unit)? = null
) {
	val builder = AlertDialog.Builder(context)
	title?.let {
		builder.setTitle(title)
	}
	message?.let {
		builder.setMessage(message)
	}
	builder.setPositiveButton(net.pokeranalytics.android.R.string.ok) { _, _ ->
		positiveAction?.invoke()
	}

	if (cancelButtonTitle != null) {
		builder.setNegativeButton(cancelButtonTitle) { _, _ ->
			negativeAction?.invoke()
		}
	} else if (showCancelButton) {
		builder.setNegativeButton(R.string.cancel) { _, _ ->
			negativeAction?.invoke()
		}
	}
	builder.show()
}

fun AppCompatTextView.setTextFormat(textFormat: TextFormat, context: Context) {
	this.setTextColor(textFormat.getColor(context))
	this.text = textFormat.text
}

fun View.hideWithAnimation() {
	isVisible = true
	animate().cancel()
	animate().alpha(0f).withEndAction { isVisible = false }.start()
}

fun View.showWithAnimation() {
	isVisible = true
	animate().cancel()
	animate().alpha(1f).start()
}

fun View.addCircleRipple() = with(TypedValue()) {
	context.theme.resolveAttribute(android.R.attr.selectableItemBackgroundBorderless, this, true)
	setBackgroundResource(resourceId)
}