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()
            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(findViewById(R.id.digit1), timeString[0])
            updateDigit(findViewById(R.id.digit2), timeString[1])
            updateDigit(findViewById(R.id.digit3), timeString[2])
            updateDigit(findViewById(R.id.digit4), timeString[3])
        }

        dateTextView.text = dateFormat.format(currentTime)
    }

    private fun updateDigit(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
        }
        imageView.setImageResource(resId)
    }

    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()
    }
}
