package com.demoscene.tv

import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.fragment.app.FragmentActivity
import java.io.File
import java.util.Calendar
import kotlin.system.exitProcess

class UpdateDialogActivity : FragmentActivity() {

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

        val message = intent.getStringExtra("message") ?: "A new demo database is available.\nPress OK to download fresh data."
        findViewById<TextView>(R.id.update_message).text = message

        val btnOk = findViewById<Button>(R.id.btn_update_ok)
        btnOk.requestFocus()

        btnOk.setOnClickListener {
            // Mark that we updated this week FIRST (before deleting anything)
            // Use commit() not apply() so it writes to disk immediately
            val calendar = Calendar.getInstance()
            val prefs = getSharedPreferences("demoscene_tv", MODE_PRIVATE)
            prefs.edit()
                .putInt("last_update_week", calendar.get(Calendar.WEEK_OF_YEAR))
                .putInt("last_update_year", calendar.get(Calendar.YEAR))
                .commit()  // SYNC write - waits for disk

            // Delete the cache file
            val cacheFile = File(filesDir, "pouet_filtered.json")
            if (cacheFile.exists()) {
                cacheFile.delete()
            }

            // Also clear any .gz version if it exists
            val cacheFileGz = File(filesDir, "pouet_filtered.json.gz")
            if (cacheFileGz.exists()) {
                cacheFileGz.delete()
            }

            // Close the entire app - next open will trigger fresh download
            finishAffinity()
            exitProcess(0)
        }
    }

    override fun onBackPressed() {
        // Don't allow back - must press OK
    }
}
