/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ir.iais.utilities.hnutils.services.db

import ir.iais.utilities.hnutils.services.db.interfaces.ISession
import java.io.Closeable

/**
 * Result Wrapper
 *
 * @param <T> Result type
 * @author yoones
</T> */
@Deprecated("Will be deleted soon.")
class Res<T > constructor(private val result: T, private val session: ISession<*>?) : Closeable {
    override fun close() {
        closeSession()
    }

    @Deprecated("")
    fun <RT> then(thenAction: (T) -> RT): RT = use { thenAction(result) }

//    @Deprecated("")
//    fun <RT> then_NotCloseSession(thenAction: (T) -> RT): RT = try {
//        thenAction(result)
//    } catch (t: Throwable) {
//        close().run { throw t }
//    }

    @Deprecated("")
    fun run(runnable: (T) -> Unit): Res<T> = try {
        runnable(result)
    } catch (e: Throwable) {
        close()
    }.let { this }

    @Suppress("MemberVisibilityCanPrivate")
    @Deprecated("")
    fun closeSession(): Unit? = session?.close()

    @Deprecated("")
    fun session(): ISession<*>? = session

    @Deprecated("")
    fun result(): T = closeSession().run { result }

//    @Deprecated("")
//    fun result_NotCloseSession(): T = result

    companion object {
        @Deprecated("Will be deleted soon. ")
        @JvmStatic
        fun <T > of(result: T): Res<T> {
            return Res(result, null)
        }
    }
}
