/****************************************************************************
 * Copyright (c) 2010-2012, EBM WebSourcing - All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the University of California, Berkeley nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ****************************************************************************/
 
package com.ebmwebsourcing.easycommons.io;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import com.ebmwebsourcing.easycommons.lang.UncheckedException;

/**
 * @author Marc Jambert - EBM WebSourcing
 */
public class IOHelper {

    private static final byte[] EMPTY_BYTE_ARRAY = new byte[0];

    private IOHelper() {
    }

    public static void close(Closeable closeable) {
        if (closeable == null)
            return;
        try {
            closeable.close();
        } catch (IOException e) {
            throw new UncheckedException(String.format(
                    "Cannot close object of class '%s'.", closeable.getClass()
                            .getSimpleName()));
        }
    }

    /**
     * Get the line of the specified file corresponding to the specified line
     * number. Each time this method is called, the file is open, read until the
     * specified line number and closed.
     * 
     * @param file
     *            the file to read the line
     * @param lineNum
     *            the number of the line in the specified file
     * @return a String containing the contents of the line, not including any
     *         line-termination characters, or null if the specified line number
     *         is greater than the line number of the file
     * 
     * @throws IOException
     *             if the file does not exist, is a directory rather than a
     *             regular file, or for some other reason cannot be opened for
     *             reading, if a security manager exists and its checkRead
     *             method denies read access to the file or if an I/O error
     *             occurs
     */
    public static final String getLine(File file, int lineNum) throws IOException {
        assert file != null;
        assert lineNum > 0;
        
        String strLine = null;

        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));

            int counter = 1;
            strLine = br.readLine();
            while (strLine != null && counter < lineNum) {
                strLine = br.readLine();
                counter++;
            }
        } finally {
            if (br != null) {
                br.close();
            }
        }

        return strLine;
    }

    
    /**
     * Read the specified file
     * 
     * @param file
     *            the file to read
     * 
     * @return the content of the file
     * 
     * @throws IOException
     *             if the file does not exist, is a directory rather than a
     *             regular file, or for some other reason cannot be opened for
     *             reading, if a security manager exists and its checkRead
     *             method denies read access to the file or if an I/O error
     *             occurs
     */
    public static final String readFileAsString(File file) throws IOException {
    	return new String(readFileAsBytes(file));
    }

    
	public static byte[] readFileAsBytes(File file) throws IOException {
		assert file != null;
		if (file.canRead() && (file.length() == 0)) return EMPTY_BYTE_ARRAY;
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(file);
			byte[] readBytes = new byte[(int) file.length()];
			int nbRead = fis.read(readBytes);
			assert nbRead == readBytes.length;
			return readBytes;
		} finally {
			IOHelper.close(fis);
		}
	}
}
