package ru.yandex.direct.libs.nonEmptyCollection.unsafe

import ru.yandex.direct.libs.nonEmptyCollection.list.NonEmptyList
import ru.yandex.direct.libs.nonEmptyCollection.map.NonEmptyMap
import ru.yandex.direct.libs.nonEmptyCollection.set.NonEmptySet

@UnsafeNonEmptyCollectionApi
fun <T> Iterable<T>.toNonEmptyList(): NonEmptyList<T> = isAlreadyNonEmptyOr {
    NonEmptyList(toList())
}

@UnsafeNonEmptyCollectionApi
fun <T> Iterable<T>.toNonEmptySet(): NonEmptySet<T> = isAlreadyNonEmptyOr {
    toSet().toNonEmptySet()
}

@UnsafeNonEmptyCollectionApi
fun <T> Set<T>.toNonEmptySet(): NonEmptySet<T> = isAlreadyNonEmptyOr {
    NonEmptySet(this)
}

@UnsafeNonEmptyCollectionApi
fun <K, V> Iterable<Pair<K, V>>.toNonEmptyMap(): NonEmptyMap<K, V> = isAlreadyNonEmptyOr {
    toMap().toNonEmptyMap()
}

@UnsafeNonEmptyCollectionApi
fun <K, V> Map<K, V>.toNonEmptyMap(): NonEmptyMap<K, V> = isAlreadyNonEmptyOr {
    NonEmptyMap(this)
}

private inline fun <Empty, reified NonEmpty> Empty.isAlreadyNonEmptyOr(
    transform: Empty.() -> NonEmpty
) = if (this is NonEmpty) this else transform(this)
