package com.example.daydreamclock

import android.os.Handler
import android.os.Looper
import android.service.dreams.DreamService
import android.widget.TextView
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

class ClockDreamService : DreamService() {

    private lateinit var dateTextView: TextView
    private lateinit var weatherTextView: TextView

    private val handler = Handler(Looper.getMainLooper())
    private val timeRunnable = object : Runnable {
        override fun run() {
            updateTime()
            
            // Blink colon
            val colon = findViewById<android.widget.ImageView>(R.id.colon)
            if (colon != null) {
                colon.alpha = if (colon.alpha > 0.1f) 0.0f else 1.0f
            }

            handler.postDelayed(this, 1000)
        }
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        // Exit dream upon user touch
        isInteractive = false
        // Hide system UI
        isFullscreen = true
        
        setContentView(R.layout.layout_dream)

        dateTextView = findViewById(R.id.dateTextView)
        weatherTextView = findViewById(R.id.weatherTextView)
        
        // Initial Update
        updateTime()
        fetchWeather()
    }

    override fun onDreamingStarted() {
        super.onDreamingStarted()
        handler.post(timeRunnable)
    }

    override fun onDreamingStopped() {
        super.onDreamingStopped()
        handler.removeCallbacks(timeRunnable)
    }

    private fun updateTime() {
        val currentTime = Date()
        val timeFormat = SimpleDateFormat("HHmm", Locale.getDefault())
        val timeString = timeFormat.format(currentTime)
        val dateFormat = SimpleDateFormat("EEE, MMM d", Locale.getDefault())

        // timeString example "1230"
        if (timeString.length == 4) {
            updateDigit(0, findViewById(R.id.digit1), timeString[0])
            updateDigit(1, findViewById(R.id.digit2), timeString[1])
            updateDigit(2, findViewById(R.id.digit3), timeString[2])
            updateDigit(3, findViewById(R.id.digit4), timeString[3])
        }

        dateTextView.text = dateFormat.format(currentTime)
    }

    private val lastDigitResIds = IntArray(4) { -1 }

    private fun updateDigit(index: Int, imageView: android.widget.ImageView, digitChar: Char) {
        val resId = when (digitChar) {
            '0' -> R.drawable.num_0
            '1' -> R.drawable.num_1
            '2' -> R.drawable.num_2
            '3' -> R.drawable.num_3
            '4' -> R.drawable.num_4
            '5' -> R.drawable.num_5
            '6' -> R.drawable.num_6
            '7' -> R.drawable.num_7
            '8' -> R.drawable.num_8
            '9' -> R.drawable.num_9
            else -> R.drawable.num_0
        }

        if (lastDigitResIds[index] != resId) {
             lastDigitResIds[index] = resId
             
             // Initial state direct set if first run (prevent pop on start) or animate
             if (imageView.drawable == null) {
                 imageView.setImageResource(resId)
             } else {
                 imageView.animate()
                     .scaleX(0.8f)
                     .scaleY(0.8f)
                     .alpha(0.5f)
                     .setDuration(150)
                     .withEndAction {
                         imageView.setImageResource(resId)
                         imageView.animate()
                             .scaleX(1.0f)
                             .scaleY(1.0f)
                             .alpha(1.0f)
                             .setDuration(150)
                             .start()
                     }
                     .start()
             }
        }
    }

    private fun fetchWeather() {
        Thread {
            try {
                // wttr.in returns simple text like "Seoul: 10C" with format=3
                // Using http for simplicity in this demo, might need usesCleartextTraffic=true if https fails on old devices, 
                // but wttr.in supports https.
                val url = java.net.URL("https://wttr.in/?format=3")
                val connection = url.openConnection() as java.net.HttpURLConnection
                connection.connectTimeout = 5000
                connection.readTimeout = 5000
                
                if (connection.responseCode == 200) {
                     val text = connection.inputStream.bufferedReader().readText()
                     handler.post {
                         weatherTextView.text = text.trim()
                     }
                } else {
                     handler.post { weatherTextView.text = "Weather Error" }
                }

            } catch (e: Exception) {
                e.printStackTrace()
                handler.post {
                    weatherTextView.text = "Offline"
                }
            }
        }.start()
    }
}
