package com.isidroid.utils

import android.text.format.DateUtils
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale

fun Date.addDays(days: Int): Date = with(Calendar.getInstance()) {
    time = this@addDays
    add(Calendar.DATE, days)
    time
}

fun Date.addMonths(months: Int): Date = with(Calendar.getInstance()) {
    time = this@addMonths
    add(Calendar.MONTH, months)
    time
}

fun Date.addSeconds(seconds: Int): Date = with(Calendar.getInstance()) {
    time = this@addSeconds
    add(Calendar.SECOND, seconds)
    time
}

fun Date.addMinutes(minutes: Int): Date = with(Calendar.getInstance()) {
    time = this@addMinutes
    add(Calendar.MINUTE, minutes)
    time
}

fun Date.addYear(year: Int): Date = with(Calendar.getInstance()) {
    time = this@addYear
    add(Calendar.YEAR, year)
    time
}

val Date?.calendar: Calendar
    get() = this?.let { Calendar.getInstance().also { calendar -> calendar.time = this } } ?: Calendar.getInstance()

val String.date: Date
    get() = try {
        SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).parse(this)!!
    } catch (t: Throwable) {
        Date()
    }

val String.dateTime: Date
    get() = try {
        SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).parse(this)!!
    } catch (t: Throwable) {
        Date()
    }

val Date.string: String
    get() = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(this)

val Date.stringDateTime: String
    get() = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()).format(this)

val Date.startDay: Date
    get() = with(Calendar.getInstance()) {
        time = this@startDay
        set(Calendar.HOUR_OF_DAY, 0)
        set(Calendar.MINUTE, 0)
        set(Calendar.SECOND, 0)
        set(Calendar.MILLISECOND, 0)
        time
    }

val Date.endDay: Date
    get() {
        val ts = startDay.addDays(1).time - 1
        return Date(ts)
    }

val Date.isToday get() = DateUtils.isToday(time)
val Date.isYesterday get() = with(Date()) { time >= addDays(-1).startDay.time && time < startDay.time }
val Date.isTomorrow get() = with(Date()) { time >= addDays(1).startDay.time && time < addDays(2).startDay.time }

val Int.asMinutesSeconds get() = with(splitToHourMinuteSeconds(this)) { String.format("%02d:%02d", second, third) }
val Int.asHoursMinutesSeconds get() = with(splitToHourMinuteSeconds(this)) { String.format("%02d:%02d:%02d", first, second, third) }

private fun splitToHourMinuteSeconds(totalSeconds: Int): Triple<Int, Int, Int> {
    val hours: Int = totalSeconds / 3600
    val minutes: Int = (totalSeconds % 3600) / 60
    val seconds: Int = totalSeconds % 60

    return Triple(hours, minutes, seconds)
}
