package app.furmeet.events.brasilfurfest

import android.app.AlertDialog
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.WindowManager
import app.furmeet.events.brasilfurfest.helper.*
import app.furmeet.events.brasilfurfest.notification.AppJobScheduler
import app.furmeet.events.brasilfurfest.schedule.ScheduleActivity
import app.furmeet.events.brasilfurfest.schedule.managers.ScheduleManager
import app.furmeet.events.brasilfurfest.schedule.managers.ScheduleManagerGetter
import com.adlerosn.brasilfurfest.R
import kotlinx.android.synthetic.main.activity_splash.*
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.uiThread

class SplashActivity : TranslatableAppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        ActivitiesForFragments[this.javaClass.simpleName] = this
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_splash)
        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)
        countdownTitle.visibility = View.GONE
        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.editionHasStarted or (eventCountdown == null)) {
                    countdownTitle.visibility = View.GONE
                    countdownData.visibility = View.GONE
                } else {
                    countdownTitle.visibility = View.VISIBLE
                    countdownData.visibility = View.VISIBLE
                    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) {
            imageSplash.setOnClickListener { launchSchedule() }
        }
        doAsync {
            Thread.sleep(if (fastStart) 100 else 3750)
            uiThread { launchSchedule() }
        }
    }

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

    private var scheduleLaunched = false

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