package net.returnvoid.io;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;

/*
 * This code is copyright (c) Diana Lange 2017
 *
 * The library is published under the Creative Commons license NonCommercial 4.0.
 * Please check https://creativecommons.org/licenses/by-nc/4.0/ for more information.
 * 
 * This program is distributed in the hope that it will be useful, but without any warranty.
 */

/**
 * A collection of helper methods to provide the export of files.
 * 
 * @author Diana Lange
 *
 */
public class ExportHelper {

	/**
	 * This class is just a collection of static functions. It should not be
	 * possible to call the constructor.
	 */
	private ExportHelper() {

	}

	/**
	 * Saves a text based file (e.g. .html, .json, .txt, .svg, ...) at the
	 * given <b>absolutePath</b> with the file name <b>filename</b>. <b>data</b>
	 * describes the content of the file. Each entry of data will be a separate
	 * line in the output file.
	 * 
	 * @param absolutePath
	 *            The absolute path where the file should be saved. If the
	 *            directory and its parents doesn't exists these directories
	 *            will be created.
	 * @param filename The name of the file which will be saved.
	 * @param data The data which will be content of the file.
	 * @return Null or the text of the exception if any occurred.
	 */
	public static String writeTextFile(String absolutePath, String filename, String... data) {

		// file with path and filename
		File file = new File(absolutePath, filename);

		// create directory if it doesn't exists yet
		if (file.getParentFile() != null) {
			file.getParentFile().mkdirs();
		}

		Writer writer = null;

		try {
			writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file.getAbsolutePath())));

			/*
			 * iterate over all Input data and add it to writer
			 */

			for (String t : data) {
				writer.write(t);
				writer.write(System.getProperty("line.separator"));
			}
		} catch (FileNotFoundException e) {
			return "Couldn't write file at " + file.getAbsolutePath() + "\n" + e;
		} catch (IOException e) {
			return "Couldn't write file at " + file.getAbsolutePath() + "\n" + e;
		} finally {

			// close the writer.

			try {
				writer.close();
			} catch (IOException e) {
				return "Couldn't close writer" + "\n" + e;
			}

		}

		return null;
	}
}
