All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.insanusmokrassar.AutoPostTelegramBot.utils.extensions.CalculatedDateTime.kt Maven / Gradle / Ivy

Go to download

It is base library for creating smart bot for simple management of channels posts

There is a newer version: 1.7.0
Show newest version
package com.github.insanusmokrassar.AutoPostTelegramBot.utils.extensions

import com.github.insanusmokrassar.AutoPostTelegramBot.utils.CalculatedDateTime
import com.github.insanusmokrassar.AutoPostTelegramBot.utils.NewDefaultCoroutineScope
import kotlinx.coroutines.*
import org.joda.time.DateTime

typealias CalculatedPeriod = Pair

fun Iterable.nearDateTime(nearTo: DateTime = DateTime.now()): DateTime? {
    var found: DateTime? = null
    forEach {
        val currentAsFuture = it.asFutureFor(nearTo)
        if (found == null || currentAsFuture.isBefore(found)) {
            found = currentAsFuture
        }
    }

    return found
}

private val futureTasksScope = NewDefaultCoroutineScope()

fun  Iterable.executeNearFuture(block: suspend () -> R): Deferred? {
    val dateTimeToTrigger: DateTime? = nearDateTime()

    return dateTimeToTrigger ?.let {
        futureTasksScope.async {
            delay(it.millis - System.currentTimeMillis())

            block()
        }
    }
}

fun Iterable.asPairs(): List {
    var first: CalculatedDateTime? = null
    val result = mutableListOf()

    forEach {
        first = first ?.let {
            currentFirst ->
            result.add(currentFirst to it)
            null
        } ?: it.let {
            _ ->
            it
        }
    }

    return result
}

fun CalculatedPeriod.isBetween(dateTime: DateTime): Boolean {
    val secondDateTime = second.asFutureFor(dateTime)
    var firstDateTime = first.asPastFor(secondDateTime)
    return dateTime.isAfter(firstDateTime) && dateTime.isBefore(secondDateTime)
}

val CalculatedPeriod.nowIsBetween: Boolean
    get() = isBetween(DateTime.now())




© 2015 - 2024 Weber Informatics LLC | Privacy Policy