package app.furmeet.events.system

import android.app.AlertDialog
import android.content.Intent
import android.content.res.ColorStateList
import android.net.Uri
import android.os.Bundle
import android.view.View
import android.view.WindowManager
import app.furmeet.events.system.helper.*
import app.furmeet.events.system.notification.AppJobScheduler
import app.furmeet.events.system.schedule.ScheduleActivity
import app.furmeet.events.system.schedule.managers.RemoteAssetsHolder
import app.furmeet.events.system.schedule.managers.ScheduleManager
import app.furmeet.events.system.schedule.managers.ScheduleManagerGetter
import app.furmeet.events.bff.R
import app.furmeet.events.bff.databinding.ActivitySplashBinding

//import kotlinx.android.synthetic.main.activity_splash.*
//import org.jetbrains.anko.doAsync
//import org.jetbrains.anko.uiThread

class SplashActivity : TranslatableAppCompatActivityWithScheduleServiceWrapped() {

    lateinit var binding: ActivitySplashBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        RemoteAssetsHolder.ensureIsBuilt(this)
        ActivitiesForFragments[this.javaClass.simpleName] = this
        super.onCreate(savedInstanceState)
        binding = ActivitySplashBinding.inflate(layoutInflater)
        val view = binding.root
        setContentView(view)
        scheduleManager.convention.colorScheme?.primaryRegular?.let {
            binding.imageSplash.setBackgroundColor(it)
        }
        resourcesAliased = this.resources
        val fastStart = intent.getBooleanExtra("fastStart", false)
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION)
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
        window.addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS)
        binding.countdownTitle.visibility = View.GONE
        binding.countdownData.visibility = View.GONE
        val scheduleManager = ScheduleManagerGetter[ScheduleManager(this@SplashActivity)]
        doAsync {
            uiThread {
                null // Tries setting banner splash in this order:
                        ?: loadSplash(scheduleManager.currentSplashAsset)
                        ?: loadSplash(scheduleManager.conventionSeries.defaultBanner[runtimeLanguage])
            }
            uiThread { AppJobScheduler(applicationContext) }
            val eventCountdown = scheduleManager.nextEditionStartCountdown
            uiThread {
                if (scheduleManager.conventionSeries.countdownOnSplash) {
                    if (scheduleManager.editionHasStarted or (eventCountdown == null)) {
                        binding.countdownTitle.visibility = View.GONE
                        binding.countdownData.visibility = View.GONE
                    } else {
                        binding.countdownTitle.visibility = View.VISIBLE
                        binding.countdownData.visibility = View.VISIBLE
                        binding.countdownData.text = eventCountdown!!.let { (f, s, t) -> "%dd %dh %dm".format(f, s, t) }
                    }
                }
                if (scheduleManager.needsToAcceptStartupTerms) {
                    val alert = AlertDialog.Builder(this@SplashActivity, R.style.AppTheme_Dialog)
                            .setTitle(getString(R.string.accept_tos_privacy))
                            .setMessage(scheduleManager.conventionSeries.startupTerms?.get(runtimeLanguage).let {
                                if (it.isNullOrBlank()) scheduleManager.startupTerms!! else it
                            }.toHtml())
                            .setPositiveButton(getString(R.string.contract_accept)) { dialogInterface, _ ->
                                scheduleManager.acceptStartupTerms()
                                dialogInterface.dismiss()
                            }
                            .setNegativeButton(getString(R.string.contract_decline)) { dialogInterface, _ -> dialogInterface.dismiss() }
                            .setOnDismissListener {
                                if (scheduleManager.needsToAcceptStartupTerms)
                                    this@SplashActivity.finish()
                                else
                                    this@SplashActivity.start()
                            }
                            .create()
                    alert.show()
                } else start(fastStart)
            }
        }
    }

    fun start(fastStart: Boolean = true) {
        if (!fastStart) {
            binding.imageSplash.setOnClickListener { launchSchedule() }
        }
        doAsync {
            Thread.sleep(if (fastStart) 100 else 3750)
            uiThread { launchSchedule() }
        }
    }

    private fun loadSplash(asset: String? = null) =
            asset?.fromCache()?.toDrawable()?.run { asImageOf(binding.imageSplash) }

    private var scheduleLaunched = false

    private fun launchSchedule() {
        synchronized(::scheduleLaunched) {
            if (scheduleLaunched) return
            scheduleLaunched = true
        }
        val uri = intent.getStringExtra("uri")
        val intent = Intent(this, ScheduleActivity::class.java)
        intent.putExtra("uri", uri)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_TASK_ON_HOME
        this.startActivity(intent)
        this.finish()
    }
}
