/*
 * @author Ranides Atterwim <ranides@gmail.com>
 * @copyright Ranides Atterwim
 * @license WTFPL
 * @url http://ranides.net/projects/assira
 */
package net.ranides.assira.io;

import java.io.Closeable;
import java.io.IOException;
import java.util.function.Consumer;
import net.ranides.assira.trace.ExceptionUtils;
import net.ranides.assira.trace.LoggerUtils;

/**
 *
 * @author Ranides Atterwim <ranides@gmail.com>
 */
public final class IOUtils {
    
    private static final org.slf4j.Logger LOGGER = LoggerUtils.getLogger();
    
    private IOUtils() {
        /* utility class */
    }
    
    public static IOException wrap(Throwable cause) {
        return (cause instanceof IOException) ? (IOException)cause : new IOException(cause);
    }
    
    public static RuntimeException rethrow(Throwable cause) {
        return ExceptionUtils.rethrow(wrap(cause));
    }
    
    public static boolean close(Closeable object) throws IOException {
        if(null != object) {
            object.close();
            return true;
        }
        return false;
    }
    
    public static boolean close(Object object) throws Exception {
        if(object instanceof Closeable) {
            ((Closeable)object).close();
            return true;
        }
        if(object instanceof AutoCloseable) {
            ((AutoCloseable)object).close();
            return true;
        }
        return false;
    }
    
    public static boolean close(Object object, Consumer<Exception> handler) {
        try {
            return close(object);
        } catch(Exception cause) {
            if(null != handler) {
                handler.accept(cause);
            } else {
                LOGGER.warn("Exception ignored on #close", cause);
            }
            return false;
        }
    }
    
}
