package risk.messagetool;

import java.util.Enumeration;
import java.util.Locale;
import java.util.Arrays;
import java.util.List;
import java.util.Comparator;
import java.util.Vector;
import java.util.HashMap;
import java.util.Map;
import java.io.File;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLClassLoader;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.BorderLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.imageio.ImageIO;
import javax.swing.UIManager;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JPopupMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JMenuBar;
import javax.swing.JToolBar;
import javax.swing.JMenu;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import javax.swing.DefaultListModel;
import javax.swing.Box;
import javax.swing.Icon;
import javax.swing.JSeparator;
import javax.swing.ImageIcon;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeSelectionModel;
import javax.swing.tree.ExpandVetoException;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.event.TreeExpansionListener;
import javax.swing.event.TreeWillExpandListener;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.text.JTextComponent;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JScrollBar;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import java.util.Iterator;
import java.util.ArrayList;
import javax.swing.JTabbedPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.ListSelectionModel;
import java.awt.event.WindowEvent;

import risk.ui.SwingGUI.SwingGUITab;

public class MessageTool extends JPanel implements ActionListener,TreeSelectionListener,TreeWillExpandListener,ListSelectionListener,SwingGUITab { // TreeExpansionListener

	private JTree tree;
	private JTree tree2;
	private Mtcomm mycomm;
	private DoublePanel doublePanel;
	private JTextField status;

	private JComboBox address;
	private JComboBox local;
	private JButton find;

	//private ClassLoader pluginLoader;
	private MyNode message;

	private JCheckBox wrap;
	private JTextField searchbox;
	private JList results;

	private Locale currentlocale;
	private JComboBox filter1;
	private JToolBar toolbar;

	public static final Comparator CASE_INSENSITIVE_ORDER = new Comparator() {

		public int compare(Object o1, Object o2) {

			return o1.toString().compareToIgnoreCase(o2.toString());

		}

	};

	public MessageTool() {

		setName("Translation Tool");

		setOpaque(false);

		setLayout( new BorderLayout() );


		JButton load = new JButton("Load");
		load.setActionCommand("load");
		load.addActionListener(this);


		wrap = new JCheckBox("Word Wrap");
		wrap.setActionCommand("wrap");
		wrap.addActionListener(this);


		toolbar = new JToolBar();

		toolbar.setFloatable(false);

		address = new JComboBox();

		address.setEditable(true);

		//address.setActionCommand("go");
		//address.addActionListener(this);

		address.getEditor().getEditorComponent().addKeyListener(

			new KeyAdapter() {
				public void keyPressed(KeyEvent e) {
					if (e.getKeyCode() == KeyEvent.VK_ENTER) {

						actionPerformed( new ActionEvent(e,e.getKeyCode(),"go") );

					}
				}
			}
		);


		JButton go = new JButton("Go");
		go.setActionCommand("go");
		go.addActionListener(this);

		JPanel addressbar = new JPanel( new BorderLayout() );
		addressbar.add( new JLabel("   Address: ") ,BorderLayout.WEST);
		addressbar.add( address );
		addressbar.add( go ,BorderLayout.EAST);

		addressbar.setOpaque(false);

		JButton add = new JButton("add Message",new ImageIcon( this.getClass().getResource("New16.gif") ));
		add.setActionCommand("add");
		add.addActionListener(this);

		JButton remove = new JButton("refresh tree",new ImageIcon( this.getClass().getResource("Refresh16.gif") ));
		remove.setActionCommand("refresh");
		remove.addActionListener(this);

		JButton save = new JButton("save Message",new ImageIcon( this.getClass().getResource("Save16.gif") ));
		save.setActionCommand("save message");
		save.addActionListener(this);

		JButton revert = new JButton("revert Message",new ImageIcon( this.getClass().getResource("Undo16.gif") ));
		revert.setActionCommand("revert");
		revert.addActionListener(this);

		toolbar.add(load);
		toolbar.addSeparator();

		toolbar.add( add );
		toolbar.add( remove );
		toolbar.addSeparator();
		toolbar.add( save );
		toolbar.add( revert );

		local = new JComboBox();
		//local.setSelectedItem( Locale.getDefault() );

		local.setActionCommand("locale");
		local.addActionListener(this);

		Dimension size = new Dimension(80,25);

		local.setMaximumSize(size);
		local.setMinimumSize(size);
		local.setPreferredSize(size);

		size = new Dimension(150,20);

		toolbar.add( Box.createHorizontalGlue() );

		toolbar.add( new JLabel("  Locale: ") );
		toolbar.add( local );

		toolbar.setRollover(true);

		//DefaultMutableTreeNode top = new DefaultMutableTreeNode("root");

		//mycomm = new TestComm(top);

		tree = new JTree((TreeNode)null);
		tree.addTreeSelectionListener(this);
		//tree.addTreeExpansionListener(this);
		tree.addTreeWillExpandListener(this);

		//tree.setRootVisible(false);

		tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);

		tree.setCellRenderer(new MyRenderer());

		JSplitPane splitPane = new JSplitPane();

		// bar = scrollPane.getHorizontalScrollBar();

		find = new JButton("find");
		find.setActionCommand("find");
		find.addActionListener(this);

		searchbox = new JTextField();
		searchbox.setActionCommand("find");
		searchbox.addActionListener(this);

		JPanel search = new JPanel( new BorderLayout() );
		JPanel stop = new JPanel( new BorderLayout() );
		stop.add( searchbox );
		stop.add( find, BorderLayout.EAST );

		results = new JList();
		results.addListSelectionListener(this);
		results.setSelectionMode( ListSelectionModel.SINGLE_SELECTION );


		filter1 = new JComboBox();

		filter1.setActionCommand("filter");
		filter1.addActionListener(this);



		JPanel advanced = new JPanel( new BorderLayout() );

		advanced.add( new JLabel("Locales: ") ,BorderLayout.WEST);
		advanced.add( filter1 );

		JPanel more = new JPanel( new BorderLayout() );
		CollapsiblePanel advanced1 = new CollapsiblePanel( advanced, "Advanced Filters" );

		more.add(advanced1 , BorderLayout.NORTH);
		more.add(new JScrollPane( results ));

		search.add( stop , BorderLayout.NORTH);
		search.add( more );

		JTabbedPane tabs = new JTabbedPane();
		tabs.add( "tree", new JScrollPane(tree) );
		tabs.add( "search" , search );

		doublePanel = new DoublePanel();
		doublePanel.setVisible(false);

		JPanel rightPanel = new JPanel( new BorderLayout() );
		rightPanel.add(doublePanel);

		splitPane.setLeftComponent( tabs );
		splitPane.setRightComponent( rightPanel );

		splitPane.setDividerLocation(200);
		splitPane.setContinuousLayout(true);

		//toolbarPanel.add(toolbar, BorderLayout.NORTH);
		//toolbarPanel.add(splitPane);


		status = new JTextField("plugin not loaded");

		status.setEnabled(false);
		status.setDisabledTextColor( getForeground() );
		status.setOpaque(false);
		wrap.setOpaque(false);

		JPanel bottom = new JPanel( new BorderLayout() );
		bottom.setOpaque(false);

		bottom.add(status);
		bottom.add(wrap,BorderLayout.EAST);

		add( addressbar , BorderLayout.NORTH);
		add( splitPane );	
		add( bottom , BorderLayout.SOUTH);


	}

	public JToolBar getToolBar() { return toolbar; }
	public JMenu getMenu() { return null; }

	private boolean actioncancelled;

	public void valueChanged(TreeSelectionEvent e) {

		MyNode node = (MyNode)tree.getLastSelectedPathComponent();

		if (node == null) { return; }

		if (actioncancelled) { actioncancelled=false; return; }

		if ( node.hasMessage() && checkChange() ) {

			//tree.setSelectionPath( new TreePath(message.getPath()) ); // rest highleghted message

			actioncancelled=true;

			tree.setSelectionPath( e.getOldLeadSelectionPath() );

			return;

		}


		String name = node.getName();

		address.removeItem(name);

		address.insertItemAt( name ,0);
		address.setSelectedIndex(0);

		if (!node.hasMessage()) { return; }

		message = node;

		redoMessage();

	}

	public boolean checkChange() {

		if ( message!=null && doublePanel.checkChange() ) {

			int result = JOptionPane.showConfirmDialog(this,"do you want to save changes to: "+message.getName(),"save?",JOptionPane.YES_NO_CANCEL_OPTION );

			if (result == JOptionPane.CANCEL_OPTION) {

				return true;

			}

			if (result == JOptionPane.YES_OPTION) {

				saveChanges();

			}

		}


		return false;

	}




	public void redoMessage() {

		if (message==null) { return; }

		try {

			doublePanel.reuse(

				message,
				null,
				currentlocale,
				mycomm
			);

			doublePanel.setVisible(true);
		}
		catch(Exception e) {

			showError("unable to load message: "+e.getMessage() );				
			e.printStackTrace();

		}


	}

	public void saveChanges() {

		try {
			if (message!=null) { doublePanel.saveChanges(); }

		}
		catch (Exception e) {

			showError("unable to save: "+e.getMessage() );

		}

	}

	public void treeWillExpand(TreeExpansionEvent e) throws ExpandVetoException {

		// go though all children of the node about to be expanded, and add there children to them
		//System.out.println(e.getPath());

		MyNode node = (MyNode)e.getPath().getLastPathComponent();

		try {

			node.loadChildren(mycomm);

		}
		catch(Exception ex) {

			showError("unable to load children: "+ex.getMessage() );
			throw new ExpandVetoException(e);

		}

		//setupChildren( (DefaultMutableTreeNode)e.getPath().getLastPathComponent() );

	}

	public void treeWillCollapse(TreeExpansionEvent e) throws ExpandVetoException {

		//System.out.println(e);

	}

	private boolean searching;
	private Result[] fullResults;

	public void actionPerformed(ActionEvent ae) {

		if (ae.getActionCommand().equals("load")) {

			if ( checkChange() ) { return; }

			load();

		}
		else if (ae.getActionCommand().equals("add")) {

			TreePath path = tree.getSelectionPath();

			if ( path !=null ) {

				MyNode node = (MyNode)path.getLastPathComponent();

				String name = JOptionPane.showInputDialog(this,"Select name:",node.getName() );

				if (name!=null) {

					addNode(name);
				}

			}

		}
		else if (ae.getActionCommand().equals("refresh")) {

			TreePath path = tree.getSelectionPath();

			if ( path !=null ) {

				MyNode node = (MyNode)path.getLastPathComponent();

				node.removeAllChildren();

				try {

					node.loadChildren(mycomm);

				}
				catch(Exception e) {

					showError("unable to load children: "+e.getMessage());

				}

				((DefaultTreeModel)tree.getModel()).reload(node);
			}

		}
		else if (ae.getActionCommand().equals("find")) {

			if (mycomm!=null && !searching) {

				searching = true;
				find.setEnabled(false);

				status.setText("Searching...");

				new Thread() {

					public void run() {

						try {

							fullResults = mycomm.search( searchbox.getText() );

							doFilter();

						}
						catch(Exception e) {

							showError("unable to search: "+e.getMessage());

							e.printStackTrace();

							status.setText("Ready");

						}

						find.setEnabled(true);
						searching=false;
					}

				}.start();
			

			}

		}
		else if (ae.getActionCommand().equals("go")) {

			String name = ((JTextComponent)address.getEditor().getEditorComponent()).getText(); //address.getSelectedItem().toString();

			if (name=="" || mycomm==null) { return; }

			MyNode node=null;

			try {

				node = getNode(name);

			}
			catch(Exception e) {

				showError("error finding node: "+e.getMessage());
				return;

			}

			if (node==null) {

				int result = JOptionPane.showConfirmDialog(this,"do you want to add: "+name,"confirm add",JOptionPane.YES_NO_OPTION );

				if (result == JOptionPane.YES_OPTION) {

					addNode( name );

				}

			}
			else {

				TreePath treepath = new TreePath(node.getPath());
				tree.setSelectionPath( treepath );
				tree.scrollPathToVisible(treepath);

				// showMessage(node); // this happens anyway when tree is updated

			}

		}
		else if (ae.getActionCommand().equals("locale")) {

			if ( checkChange() ) {

				local.setSelectedItem( currentlocale );
				return;

			}

			currentlocale = (Locale)local.getSelectedItem();

				try {

					if (message!=null) { doublePanel.resetLocale( currentlocale ); }

				}
				catch(Exception e) {

					showError( "unable to setup locale: "+e.getMessage() );

				}



		}
		else if (ae.getActionCommand().equals("wrap")) {


			doublePanel.setWrap( wrap.isSelected() );



		}
		else if (ae.getActionCommand().equals("save message")) {

			saveChanges();

		}
		else if (ae.getActionCommand().equals("revert")) {


			if (message!=null) { doublePanel.revert(); }


		}
		else if (ae.getActionCommand().equals("filter")) {

			doFilter();
		}
		else {

			System.out.println( ae.getActionCommand() );

		}

	}

	private void doFilter() {

		if (fullResults!=null) {

			Result[] res = filter(fullResults);

			Arrays.sort(res,CASE_INSENSITIVE_ORDER);

			results.setListData( res );

			status.setText("Found "+res.length+" results");

		}
	}

	private Result[] filter(Result[] res) {

		Vector v = new Vector();

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

			if (

				(filter1.getSelectedIndex()==0 || filter1.getSelectedItem()==res[c].locale || ( res[c].locale !=null && res[c].locale.equals( filter1.getSelectedItem() )) )

			) {
				v.add(res[c]);
			}

		}

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

	}

	public void  valueChanged(ListSelectionEvent lse) {

		if (!lse.getValueIsAdjusting()) {

			Result r = (Result)results.getSelectedValue();

			if (r!=null) {

				MyNode node=null;

				try {

					node = getNode( r.node );

					if (node==null) { throw new Exception("null"); }

				}
				catch(Exception e) {

					showError("error finding node: "+e.getMessage());
					return;

				}

				TreePath treepath = new TreePath(node.getPath());
				tree.setSelectionPath( treepath );
				tree.scrollPathToVisible(treepath);

				if (r.locale!=null) { local.setSelectedItem( r.locale ); }

			}

		}

	}

	public void exit() { // yura@todo: this needs to be called

		if ( !checkChange() ) {

			System.exit(0);

		}

	}

	public void showError(String s) {

		JOptionPane.showMessageDialog(this, s, "Error", JOptionPane.ERROR_MESSAGE);

	}

	public void addNode(String name) {

		//YURA:TODO put in more checks here

		if (name.equals("") || name.charAt(0)=='.' || name.charAt(name.length()-1)=='.'|| name.indexOf("..")!=-1) {

			showError( "unable to create message\nbad name: "+name );

		}
		else {

			try {

				MyNode newnode = addNode(name, (MyNode) tree.getModel().getRoot() );

				TreePath treepath = new TreePath(newnode.getPath());

				tree.setSelectionPath( treepath );

				tree.scrollPathToVisible(treepath);

				// not needed as message is only updated when saved
				//mycomm.addNode( newnode );

			}
			catch(Exception e) {

				showError("unable to create node: "+e.getMessage() );

			}

		}

	}

	public MyNode addNode(String s,MyNode n) throws Exception {

		n.loadChildren(mycomm);

		if (s.indexOf('.')==-1) {

			Enumeration en = n.children();

			MyNode exists=null;

			while (en.hasMoreElements()) {

				MyNode node = (MyNode)en.nextElement();

				if ( node.getUserObject().equals(s) ) {

					if ( node.hasMessage() ) {

						throw new Exception("node already exists");

					}
					else {

						exists=node;
						node.setHasMessage(true);

					}

				}

			}

			if (exists==null) {

				MyNode node = new MyNode(s,true);

				n.add(node);

				//((DefaultTreeModel)tree.getModel()).insertNodeInto(node,n,0);

				exists = node;
			}

			((DefaultTreeModel)tree.getModel()).reload(n);

			return exists;

		}
		else {

			// split the name up
			String name = s.substring(0, s.indexOf('.'));			// things b4 first dot
			String name2 = s.substring(s.indexOf('.')+1,s.length());	// things after first dot

			Enumeration en = n.children();

			while (en.hasMoreElements()) {

				MyNode node = (MyNode)en.nextElement();

				if ( node.getUserObject().equals(name) ) {

					node.setHasChildren(true);

					return addNode( name2 ,node);

				}

			}


			MyNode node = new MyNode(name,false);

			n.add(node);
			((DefaultTreeModel)tree.getModel()).reload(n);


			//((DefaultTreeModel)tree.getModel()).insertNodeInto(node,n,0);

			return addNode( name2 ,node);


		}

	}

	public MyNode getNode(String name) throws Exception {


		String[] names = name.split("\\.");

		MyNode node = (MyNode) tree.getModel().getRoot();

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

			if (names[c]=="") { return null; }

			node.loadChildren(mycomm);

			node = node.getChild(names[c]);

			if (node==null) { return null; }

		}

		return node;

	}

	public void load() {

	    try {

		Mtcomm mycomm1 = new RiskComm();

		if (mycomm1.load()) {

			Locale[] locales = mycomm1.getLocales();

			if (locales==null || locales.length==0 ) {

				throw new Exception("unable to get info from plugin");

			}

			fullResults=null;

			MyNode root = new MyNode("ROOT",false,true);

			root.loadChildren(mycomm1);

			((DefaultTreeModel)tree.getModel()).setRoot( root );

			doublePanel.setVisible(false);

			address.removeAllItems();

			message=null;

			local.setModel( new DefaultComboBoxModel( locales ) );

			currentlocale=locales[0];

			results.setListData( new Object[] { } );

			filter1.setModel( new DefaultComboBoxModel( locales ) );
			filter1.insertItemAt("ALL",0);
			filter1.insertItemAt( null ,1);
			filter1.setSelectedIndex(0);

			status.setText("Ready");

			mycomm = mycomm1;

		}

	    }
	    catch(Exception ex) {

		showError( ex.toString() );

	    }


	}

	class MyRenderer extends DefaultTreeCellRenderer {
	    Icon fc;
	    Icon fcm;
	    Icon fo;
	    Icon fom;
	    Icon m;

	    public MyRenderer() {

	        fc = new ImageIcon( this.getClass().getResource("fc.gif") );
	        fcm = new ImageIcon( this.getClass().getResource("fcm.gif") );
	        fo = new ImageIcon( this.getClass().getResource("fo.gif") );
	        fom = new ImageIcon( this.getClass().getResource("fom.gif") );
	        m = new ImageIcon( this.getClass().getResource("m.gif") );

	    }

	    public Component getTreeCellRendererComponent(
	                        JTree tree,
	                        Object value,
	                        boolean sel,
	                        boolean expanded,
				boolean leaf,
	                        int row,
	                        boolean hasFocus) {

	        super.getTreeCellRendererComponent(
	                        tree, value, sel,
	                        expanded, leaf, row,
	                        hasFocus);

		MyNode node = (MyNode)value;

		if ( leaf && node.hasMessage()) {
			setIcon(m);
		}
		else if (expanded && node.hasMessage()) {
			setIcon(fom);
		}
		else if (!expanded && node.hasMessage()) {
			setIcon(fcm);
		}
		else if (expanded && !node.hasMessage()) {
			setIcon(fo);
		}
		else { // if (!expanded && !node.hasMessage()) {
			setIcon(fc);
		}

	        return this;
	    }

	}

}

