package de.beyondsoft.ownchat.utils;

import android.support.annotation.NonNull;

/**
 * Created by imarneanu on 2/9/17.
 */
public final class Preconditions {

    private Preconditions() {
    }

    /**
     * Throws an {@link IllegalStateException} if {#condition} is false
     *
     * @param condition The condition
     * @param message   The exception message
     * @param args      Optional args
     */
    public static void checkState(boolean condition, String message, Object... args) {
        if(!condition) {
            throw new IllegalStateException(formatMessage(message, args));
        }
    }

    /**
     * Throws a {@link IllegalArgumentException} if {#condition} is false
     *
     * @param condition The condition
     * @param message   The exception message
     * @param args      Optional args
     */
    public static void checkArgument(boolean condition, String message, Object... args) {
        if(!condition) {
            throw new IllegalArgumentException(formatMessage(message, args));
        }
    }

    /**
     * Throws a {@link NullPointerException} if {#thing} is null
     *
     * @param thing   The thing
     * @param message The exception message
     * @param args    Optional args
     */
    @NonNull
    public static <T> T checkNotNull(T thing, String message, Object... args) {
        if(thing == null) {
            throw new NullPointerException(formatMessage(message, args));
        }

        return thing;
    }

    /**
     * Throws a {@link IllegalStateException} if {#thing} is not null
     *
     * @param thing   The thing
     * @param message The exception message
     * @param args    Optional args
     */
    public static void checkNull(Object thing, String message, Object... args) {
        if(thing != null) {
            throw new IllegalStateException(formatMessage(message, args));
        }
    }

    /**
     * Throws an {@link IllegalStateException} if {#condition} is false
     *
     * @param condition The condition
     */
    public static void checkState(boolean condition) {
        checkState(condition, "condition not met");
    }

    /**
     * Throws an {@link NullPointerException} if <code>thing</code> is null
     *
     * @param thing The thing
     */
    @NonNull
    public static <T> T checkNotNull(T thing) {
        return checkNotNull(thing, "condition not met");
    }

    private static String formatMessage(String message, Object... args) {
        return String.format(message, args);
    }
}
