/*
 * Copyright (c) 2010-2020 Belledonne Communications SARL.
 *
 * This file is part of linphone-android
 * (see https://www.linphone.org).
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package org.linphone.utils

/**
 * Helper class to create singletons like CoreContext.
 */
open class SingletonHolder<out T : Any, in A>(val creator: (A) -> T) {
    @Volatile private var instance: T? = null

    fun exists(): Boolean {
        return instance != null
    }

    fun destroy() {
        instance = null
    }

    fun get(): T {
        // Will throw NPE if needed
        return instance!!
    }

    fun create(arg: A): T {
        val i = instance
        if (i != null) {
            return i
        }

        return synchronized(this) {
            val i2 = instance
            if (i2 != null) {
                i2
            } else {
                val created = creator(arg)
                instance = created
                created
            }
        }
    }

    fun required(arg: A): T {
        return instance ?: create(arg)
    }
}
