package rasel.lunar.launcher.view

import android.content.Context
import android.os.Handler
import android.os.Looper
import android.text.SpannableString
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.style.AbsoluteSizeSpan
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView
import java.text.SimpleDateFormat
import java.util.Date


class DateTimeView : AppCompatTextView {
    lateinit var mHandler : Handler
    val simpleTimeFormat = SimpleDateFormat("a HH:mm:ss")
    val simpleDateFormat = SimpleDateFormat("yyyy년 MM월 W주차 dd일 E요일")
    var runable = {
        setTime()
    }
    constructor(context: Context) : super(context)

    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {

    }

    init {
        mHandler = Handler(Looper.getMainLooper())
        mHandler.postDelayed(runable, DateTimeView.DALEY)
    }

    val spannableBuilder = SpannableStringBuilder()

    private fun setTime() {
        spannableBuilder.clear()
        val now = Date(System.currentTimeMillis())
        val time = SpannableString(simpleTimeFormat.format(now))
        val date = SpannableString(simpleDateFormat.format(now))
        spannableBuilder.append(time)
        spannableBuilder.setSpan(AbsoluteSizeSpan(48,true), 0, time.length , Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        spannableBuilder.append("\n")
        spannableBuilder.append(date)
        var start = time.length + "\n".length
        spannableBuilder.setSpan(AbsoluteSizeSpan(30,true), start , start+date.length , Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        mHandler.removeCallbacks(runable)
        setText(spannableBuilder)
        mHandler.postDelayed(runable, DateTimeView.DALEY)
    }

    companion object {
        const val DALEY = 500L
    }
}