package Cluedo.API;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.FileWriter;
import java.io.*;

import javax.swing.*;

/**
 * Simplifies and handles external file access, this works with files inside a .jar.
 * 
 * @author Alex Ellis
 */
public class Resources {
	static String defaultLinuxBrowser = Constants.DEFAULT_LINUX_WEBBROWSER;

	/**
	 * Grab a BufferedReader for a text from a file, this is "jar-proof".
	 * @param fileName
	 *               Required file.
	 * @param sclass
	 *               Should always be "this".
	 * @return
	 *       An instance of BufferedReader pointing to fileName
	 */
	public static BufferedReader getTextFileLink(String fileName, Object sclass) throws IOException {
		InputStreamReader fileStream = null;
		try {
			fileStream = new InputStreamReader(
				sclass.getClass().getResourceAsStream(fileName));
		}
		catch(Exception IO) {
			throw new IOException();
		}
			
		return new BufferedReader(fileStream);
	}
	/**
	 * Cat the text from a file into a string, this is "jar-proof".
	 * @param fileName
	 *               Required file.
	 * @param sclass
	 *               Should always be "this".
	 * @return
	 *       The content of file fileName or "" for a failed load
	 */
	public static String catTextFile(String fileName, Object sclass) throws IOException {
		StringBuffer buffer = new StringBuffer("");
		String line = "";

		java.io.BufferedReader fstream = null;
		
		try {
			fstream = getTextFileLink(fileName, sclass);
			while((line = fstream.readLine()) != null) {
				buffer.append(line + "\n");
			}
			fstream.close();
		}
		catch(Exception IO) {
			throw new IOException();
		}
		
		return buffer.toString();
	}
	
	public static String catTextFileExt(String fileName, Object sclass) throws IOException {
		StringBuffer buffer = new StringBuffer("");
		String line = "";

		java.io.BufferedReader fstream = null;
		
		try {
			fstream = new BufferedReader(new FileReader(fileName));
			while((line = fstream.readLine()) != null) {
				buffer.append(line + "\n");
			}
			fstream.close();
		}
		catch(Exception IO) {
			throw new IOException();
		}
		
		return buffer.toString();
	}
	
	/**
	 * Dump a text file to disk.
	 * 
	 * @param fileName
	 * @param text
	 * @param sclass
	 * @throws IOException
	 */
	public static void dumpTextFile(String fileName, String text) throws IOException {

		try {
			
		  	BufferedWriter fstream = new BufferedWriter( new FileWriter(fileName));
		  	fstream.write(text);
		  	fstream.flush();
		  	fstream.close();
		  	

		}
		catch(Exception IO) {
			System.out.println("dumpTextFile can't access file " + fileName);
			throw new IOException();
		}
		
	}
	
	/**
	 * Configures the look and feel according to the host operating system
	 */
	public static void configureUI() {
		if( new File ("no_interface_configuration").exists() == false ) {
			String operatingSystem = System.getProperty("os.name");
			String javaVersion = System.getProperty("java.version");
			System.out.println("[Resources:configureUI] Running on: " + operatingSystem);
        		
			try {
				if(operatingSystem != null)
					if (javaVersion.startsWith("1.4")) {
						// In Linux try to set the look to "GTKLookAndFeel"
					   	if(operatingSystem.startsWith("Linux")) {
					   		try {
					   			UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");
					   		}
					   		catch(Exception notFound) {
					   			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
					   		}
					   	}
					   	else {
					   		UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
					   	}
					}
			}
			catch (Exception e) {
				System.out.println("[Resources:configureUI] Can't set look and feel.");
			    e.printStackTrace();
			}
		}
	}
	
  /**
    * Method opens a document whether HTML, JPG, TXT or otherwise in the default webbrowser<br>
    * it checks operating system first. In Windows we let the Windows system find a handler<br>
    * but in Linux we use the default mozilla.<br>
    * Throws appropriate exceptions, see example in OpenHTML.java for a sample usage.
    * <br>
    *
    * @parameter fileName
    * The filename of the file we want to open in a web browser.
    * 
    *
    */	
  public static void openDocument(String fileName) throws FileNotFoundException, RuntimeException  {
  	String command = "";
  	File targetFile = new File(fileName);

	if(targetFile.exists() == true) {
        	if (System.getProperty("os.name").startsWith("Windows"))
  			command = "rundll32 url.dll,FileProtocolHandler";
        	else
		  	command = defaultLinuxBrowser;
        	
  		try {
  		    Process p = Runtime.getRuntime().exec( 
  		    				command + " file://" + targetFile.getAbsolutePath() );
  		}
  		catch(Exception Error) {
  			throw new RuntimeException();
      		}
      	}
	else
		throw new FileNotFoundException();
  }
}