package risk.messagetool;

import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.JFileChooser;
import java.io.File;
import javax.swing.JOptionPane;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Properties;
import java.util.Enumeration;
import java.util.Vector;
import java.util.Collections;
import java.util.Locale;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Arrays;
import javax.swing.filechooser.FileFilter;

public class RiskComm implements Mtcomm {

	private Properties props;
	private HashMap map;
	private String name;
	private String extension;

	public boolean load() throws Exception {

	    JFileChooser fc = new JFileChooser("risk/engine/translation");
/*
	    javax.swing.filechooser.FileFilter fileFilter = new javax.swing.filechooser.FileFilter() {
		public boolean accept(File file) {
		    //return (file.isDirectory());
		    return ( file.isFile() );
		}
		public String getDescription() {
		    //return "All Directories";
		    return "Risk File";
		}
	    };

	    fc.setFileSelectionMode( JFileChooser.DIRECTORIES_ONLY );
	    fc.setFileFilter(fileFilter);
	    fc.setAcceptAllFileFilterUsed(false);
	    fc.setDialogTitle("Select Image Directory");
*/

	    FileFilter ff = new FileFilter() {

		public boolean accept(File f) {

			return (f.isDirectory() || ( f.getName().equals("Risk.properties") || f.getName().equals("DefaultMaps.properties") || f.getName().equals("DefaultCards.properties") ) );

		}
		public String getDescription() {

			return "Risk Translation Files (Risk.properties,DefaultMaps.properties,DefaultCards.properties)";
		}
	    };




	    fc.addChoosableFileFilter( ff );
	    fc.addChoosableFileFilter( new FileFilter() {

		public boolean accept(File f) {

			return (f.isDirectory() || f.getName().equals("risk.ini")  );

		}
		public String getDescription() {

			return "Risk Settings File (risk.ini)";
		}
	    } );
	    fc.addChoosableFileFilter( new risk.engine.RiskFileFilter( risk.engine.RiskFileFilter.RISK_PROPERTIES_FILES ) );




	    fc.setFileFilter( ff );

	    fc.setFileSelectionMode( JFileChooser.FILES_ONLY );

            int returnVal = fc.showDialog(null , "Select");

	    // if a file is selected instead of a dir, the return value is the same as if you cancel

            if (returnVal == JFileChooser.APPROVE_OPTION) {

		// Write your code here what to do with selected file


		// get all propaties files
		File file = fc.getSelectedFile();

		//File[] files = file.listFiles();


		props = new Properties();

		load( props, new FileInputStream(file) );

		map = new HashMap();

		name = file.getPath();

		extension = name.substring(name.lastIndexOf( '.'), name.length() ); // this gives ".properties"

		name = name.substring( 0, name.lastIndexOf( '.'));

		return true;

            } else {

		return false;

	    }

	}

	public void load(Properties p,FileInputStream in) throws Exception {

		p.load( in );

	}

	public void store(Properties p,FileOutputStream out,String a) throws Exception {

		p.store( out , a);

	}

	public void addChildren(MyNode node) {

		String name = node.getName();

		if (name.length() >0) { name = name+"."; }

		Enumeration en = props.propertyNames();

		while (en.hasMoreElements()) {

			String s = en.nextElement().toString();			// swing.setup.title	swing.mainbox

			if ( s.startsWith(name) ) {

				// cut off name and first dot
				s = s.substring(name.length(),s.length());	// setup.title		mainbox

				boolean children=false;
				boolean message=false;

				// cut off everything after dot, if there is any

				if (s.indexOf('.')!=-1) {			// setup		mainbox 

					children=true;				// ########## it has children!!!!
					s = s.substring(0,s.indexOf('.'));

				}
				else {
					message=true;				// ########## it has a message!!!!
				}


				MyNode newnode = new MyNode(s,message,children);

				node.add(newnode);
			}

		}


	}

	public String getMessage(MyNode node, Locale l) {

		return getLocaleProperties(l).getProperty( node.getName() );

	}

	public Properties getLocaleProperties(Locale l) {

		if (l==null) { return props; }

		if (!map.containsKey(l)) {

			Properties pp = new Properties();

			try {

				load(pp, new FileInputStream( new File(name+"_"+l+extension) ) );

			}
			catch(Exception e) { System.out.println("not found: "+l); }

			map.put(l,pp);

		}

		return (Properties)map.get(l);

	}

	public String toString() {

		return "Risk Language Plugin\nBy Yura Mamyrin (yura@yura.net)\nRisk site: http://jrisk.sf.net/";

	}

	public void saveMessage(MyNode node, Locale l, String message) throws Exception {

		Properties p = getLocaleProperties(l);

		if (message==null) {

			p.remove( node.getName() );

		}
		else {

			p.setProperty(node.getName(),message);

		}

		FileOutputStream fos = new FileOutputStream( name+  ((l==null)?(""):("_"+l))  +extension );

		// java 1.4 fucks this up, so cant have more then 1 line
		store(p,fos,"Risk Translation Tool "+risk.engine.Risk.RISK_VERSION ); // +"\nSaved with "+toString() ); 

	}

	public Locale[] getLocales() {

		Locale[] a = Locale.getAvailableLocales();
		Arrays.sort(a,MessageTool.CASE_INSENSITIVE_ORDER);
		return a;

	}

	public Result[] search(String s) throws Exception {

		Locale[] mylocs = Locale.getAvailableLocales();

		Vector results = new Vector();

		s = s.toLowerCase();

		findString(null,props,s,results);

		for (int c=0; c<mylocs.length; c++) {

			findString(mylocs[c], getLocaleProperties(mylocs[c]),s,results);

		}

		return (Result[])results.toArray( new Result[results.size()] );

	}

	private void findString(Locale l, Properties p,String s,Vector r) {

		Iterator it = p.entrySet().iterator();

		while (it.hasNext()) {

			java.util.Map.Entry me = (java.util.Map.Entry)it.next();

			String key = (String)me.getKey();
			String value = (String)me.getValue();

			if ( value.toLowerCase().indexOf(s) > -1) {

				Result res = new Result();

				res.node = key;
				res.locale = l;

				r.add( res );

			}

		}


	}

}
