package com.demoscene.tv

import android.content.Intent
import android.os.Bundle
import android.widget.TextView
import androidx.fragment.app.FragmentActivity
import com.demoscene.tv.data.PouetCache
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.util.Calendar

class LoadingActivity : FragmentActivity() {

    private lateinit var statusText: TextView
    private lateinit var counterText: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_loading)

        statusText = findViewById(R.id.status_text)
        counterText = findViewById(R.id.counter_text)

        // Check for Thursday update FIRST
        if (shouldShowUpdatePrompt()) {
            showUpdateDialog()
            return
        }

        startLoading()
    }

    private fun shouldShowUpdatePrompt(): Boolean {
        // Only check if we have cached data (not first run / not after wipe)
        val cacheFile = java.io.File(filesDir, "pouet_filtered.json")
        if (!cacheFile.exists()) {
            return false
        }

        val calendar = Calendar.getInstance()
        val dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK)
        val hourOfDay = calendar.get(Calendar.HOUR_OF_DAY)

        // Thursday = Calendar.THURSDAY (5), after 04:00
        if (dayOfWeek == Calendar.THURSDAY && hourOfDay >= 4) {
            val prefs = getSharedPreferences("demoscene_tv", MODE_PRIVATE)
            val lastUpdateWeek = prefs.getInt("last_update_week", -1)
            val lastUpdateYear = prefs.getInt("last_update_year", -1)

            val currentWeek = calendar.get(Calendar.WEEK_OF_YEAR)
            val currentYear = calendar.get(Calendar.YEAR)

            // Only prompt if we haven't updated this week
            return !(lastUpdateWeek == currentWeek && lastUpdateYear == currentYear)
        }

        return false
    }

    private fun showUpdateDialog() {
        val intent = Intent(this, UpdateDialogActivity::class.java)
        intent.putExtra("message", "Weekly database update available.\nPress OK to download fresh data.")
        startActivity(intent)
        finish()
    }

    private fun startLoading() {
        CoroutineScope(Dispatchers.Main).launch {
            val hasCache = PouetCache.isCached(this@LoadingActivity)

            if (hasCache) {
                statusText.text = "LOADING CACHE..."
                delay(500)
                launchHub()
            } else {
                // No cache - need to download
                statusText.text = "DOWNLOADING DEMO DATABASE..."
                
                // Start download in background
                CoroutineScope(Dispatchers.IO).launch {
                    PouetCache.downloadAndCache(this@LoadingActivity) { progress ->
                        CoroutineScope(Dispatchers.Main).launch {
                            if (progress.startsWith("Processed")) {
                                counterText.text = progress
                            } else {
                                statusText.text = progress.uppercase()
                            }
                        }
                    }
                }

                // Wait for cache to be ready
                while (!PouetCache.isCached(this@LoadingActivity)) {
                    delay(1000)
                }

                statusText.text = "BUILDING CATEGORIES..."
                counterText.text = ""
                delay(500)
                launchHub()
            }
        }
    }

    private fun launchHub() {
        startActivity(Intent(this, HubActivity::class.java))
        finish()
    }
}
