
import java.io.*;
import java.io.File;
import java.awt.*;
import java.net.*;
import java.util.*;
import java.text.*;
import java.beans.*;
import java.awt.event.*;

import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;
import javax.swing.plaf.*;
import javax.swing.plaf.metal.*;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;

public class Exp_Out extends JDialog implements ActionListener {

	static JDialog exp_d;
	static JPanel fullPanel, probj2expPanel, topGridPanel, midGridPanel;
	static JPanel probjTAPanel, exptypePanel, propathPanel, btmbutPanel;
	static JPanel defdirPanel, outpathPanel;
	static JFileChooser dap_fc,drw_fc,pad_fc,pa_fc,dir_fc,proe_bat_fc,dir_out_fc,usr_ws_fc;

	static JButton probj_but, ExitBut, SaveBut, ExecBut, exp_obj_but, outpath_but, defdir_but;
	static JTextField exptypeField, propathField, outpathField, defdirField;
	static JTextArea probj2exp, probjTA;
	static JScrollPane textScroller, textScrollerTA;

	static String exp_out_propval, proe_path_propval, proe_name_propval, pro_batch_propval;
	static String exp_out_stg, exp_txtnm, call_exp_out_stg, call_exp_batnm, exp_out_DIR;
	static String exptypeStg, addbatchStg, propathStg, curdirStg, bat_cmd, curdefdir;
	static String dxf_exp_form;

	static String[] probjStg;
	static String path_propsfile = "exp_path.properties";
	static String[] exp_val = { "IGES","STEP","DXF","VRML" };
	static File[] selectedFiles;
	static File file_usr_ws;
	static Process procs;

	SimpleDateFormat df = new SimpleDateFormat ("MMddyy_HHmmss", Locale.getDefault());
	Date tm = new Date();
	String DateStg = df.format(tm);

	Properties path_props = new Properties ();

	BAT_Filter bat_filter = new BAT_Filter();
	DIR_Filter dir_filter = new DIR_Filter();
	DRW_Filter drw_filter = new DRW_Filter();
	ASM_PRT_Filter ap_filter = new ASM_PRT_Filter();
	DRW_ASM_PRT_Filter dap_filter = new DRW_ASM_PRT_Filter();

    public Exp_Out() {

		exp_d=new JDialog(new JFrame(),"Batch Export - Engineering Application Tool",true);
		exp_d.setResizable( false );

		exp_d.addWindowListener( new WindowAdapter() {
			public void windowClosing( WindowEvent e ) { System.exit(0); }
		});

		try {
			UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
		}
		catch (Exception exc) {}

		// ProE & Export Out Path Properties file
		try {
			path_props.load(new BufferedInputStream(new FileInputStream(path_propsfile)));
		}
		catch (IOException e) {}

		String exp_out_propval		= path_props.getProperty("exp_out_path");
		String proe_path_propval 	= path_props.getProperty("proe_bat_path");
		String proe_name_propval 	= path_props.getProperty("proe_bat_name");
		String pro_batch_propval 	= path_props.getProperty("pro_batch_bat_name");
		String proi_ws_propval 		= path_props.getProperty("proi_ws_path");
		final String dxf_exp_form	= path_props.getProperty("dxf_export_format");

		String exp_out_DIR			= exp_out_propval;
		String proe_bat_path		= proe_path_propval;
		final String full_proe_bat	= proe_path_propval + "\\" + proe_name_propval;
		String full_pro_batch_bat	= proe_path_propval + "\\" + pro_batch_propval;

		String curdirStg 			= System.getProperty( "user.dir" );
		String usrnmStg 			= System.getProperty( "user.name" );
		String exp_out_stg			= "EXP_OUT_" + DateStg + ".txt";
		final String exp_txtnm		= curdirStg + "\\" + exp_out_stg;
		String call_exp_out_stg		= "CALL_EXP_OUT_" + DateStg + ".bat";
		final String call_exp_batnm	= curdirStg + "\\" + call_exp_out_stg;
		final String bat_cmd		= full_pro_batch_bat + " -text " + full_proe_bat  + " " + exp_txtnm;
		String usr_ws_path			= proi_ws_propval + "\\" + usrnmStg + "\\.proi\\exp_out\\backup";
		String usr_ws_proi_path		= proi_ws_propval + "\\" + usrnmStg + "\\.proi";

		file_usr_ws = new File( usr_ws_path );
		curdefdir = usr_ws_path;
		if(!file_usr_ws.exists()) {
			file_usr_ws = new File( usr_ws_proi_path );
			curdefdir = usr_ws_proi_path;
			if(!file_usr_ws.exists()){
				file_usr_ws = new File( curdirStg );
				curdefdir = curdirStg;
			}
		}

		usr_ws_fc	= new JFileChooser(file_usr_ws);
		dap_fc		= new JFileChooser(curdefdir);
		drw_fc		= new JFileChooser(curdefdir);
		pad_fc		= new JFileChooser(curdefdir);
		pa_fc		= new JFileChooser(curdefdir);
		dir_fc		= new JFileChooser(curdefdir);
		dir_out_fc	= new JFileChooser(exp_out_DIR);
		proe_bat_fc	= new JFileChooser(proe_bat_path);

		fullPanel = new JPanel();
		fullPanel.setBorder(new EmptyBorder(1,1,1,1));
		fullPanel.setLayout(new BorderLayout());

		topGridPanel = new JPanel();
		GridBagLayout gbc0 = new GridBagLayout();
		topGridPanel.setLayout(gbc0);

		// Export Output Type Panel
		exptypePanel = new JPanel();

		JLabel exptypeLabel = new JLabel ("1) Export Output Type:");
		exptypePanel.add(exptypeLabel);

		exptypeField = new JTextField(exp_val[0],6);
		exptypePanel.add(exptypeField);

		final JComboBox exptypeComboBox = new JComboBox(exp_val);
		exptypeComboBox.setSelectedItem(exp_val[0]);
		exptypePanel.add(exptypeComboBox);

		exptypeComboBox.addItemListener(
			new ItemListener() {
				public void itemStateChanged( ItemEvent e ) {
					if( e.getStateChange() == ItemEvent.SELECTED ){
						exptypeField.setText("" + ((JComboBox)e.getSource()).getSelectedItem());
					}
				}
			}
		);

		// ProE Object Text Area label & Button
		JLabel probjTALabel = new JLabel("  2) Select Files To Export:");
		exptypePanel.add(probjTALabel);

		probj_but = new JButton("Select File(s)");
		probj_but.addActionListener(this);
		exptypePanel.add(probj_but);

		// Default Directory Path Panel
		defdirPanel= new JPanel();

		JLabel defdirLabel = new JLabel("Select From Path");
		defdirPanel.add(defdirLabel);

		defdirField = new JTextField(curdefdir,25);
		defdirPanel.add(defdirField);

		defdir_but = new JButton("Select Dir/Folder");
		defdir_but.addActionListener(this);
		defdirPanel.add(defdir_but);

		// ProE Object Text Area Panel
		probjTAPanel= new JPanel();
		probjTAPanel.setLayout(new BorderLayout());

		JLabel probjTAsepLabel = new JLabel("File(s) Selected List:");
		probjTAPanel.add(probjTAsepLabel, BorderLayout.NORTH);

		probjTA = new JTextArea("",7,50);
		probjTA.setLineWrap(false);

		textScrollerTA = new JScrollPane(probjTA);
		probjTAPanel.add(textScrollerTA);

		exp_obj_but = new JButton("3) ADD BATCH ENTRY");
		exp_obj_but.addActionListener(this);
		probjTAPanel.add(exp_obj_but, BorderLayout.SOUTH);

		topGridPanel.add(exptypePanel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0
			,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(1, 1, 1, 1), 1, 0));
		topGridPanel.add(defdirPanel, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0
			,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(1, 1, 1, 1), 1, 0));
		topGridPanel.add(probjTAPanel, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0
			,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(1, 1, 1, 1), 1, 0));

		midGridPanel = new JPanel();
		GridBagLayout gbc1 = new GridBagLayout();
		midGridPanel.setLayout(gbc1);

		// Export Output Field Panel
		probj2expPanel = new JPanel();
		probj2expPanel.setLayout(new BorderLayout());

		JLabel probj2expLabel = new JLabel("Export Output Type || Files To Export:");
		probj2expPanel.add(probj2expLabel, BorderLayout.NORTH);

		probj2exp = new JTextArea("",7,50);
		probj2exp.setLineWrap(false);

		textScroller = new JScrollPane( probj2exp);
		probj2expPanel.add(textScroller, BorderLayout.SOUTH);

		// Output Path Panel
		outpathPanel= new JPanel();

		JLabel outpathLabel = new JLabel("Export Output Path");
		outpathPanel.add(outpathLabel);

		outpathField = new JTextField(exp_out_DIR,25);
		outpathPanel.add(outpathField);

		outpath_but = new JButton("Select Dir/Folder");
		outpath_but.addActionListener(this);
		outpathPanel.add(outpath_but);

		midGridPanel.add(probj2expPanel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0
			,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(1, 1, 1, 1), 1, 0));
		midGridPanel.add(outpathPanel, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0
			,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(1, 1, 1, 1), 1, 0));

		btmbutPanel = new JPanel();
		btmbutPanel.setLayout ( new FlowLayout(FlowLayout.CENTER) );

		SaveBut = new JButton("SAVE BATCH FILE");
		SaveBut.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				SaveSelected( exp_txtnm, full_proe_bat );
				SaveSelectedBat( bat_cmd, dxf_exp_form, call_exp_batnm );
		}});
		btmbutPanel.add(SaveBut);

		ExitBut = new JButton("EXIT");
		ExitBut.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) { System.exit(0); }
		});
		btmbutPanel.add(ExitBut);

		ExecBut = new JButton("EXECUTE BATCH FILE");
		ExecBut.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				RunCmdInt( call_exp_batnm );
		}});
		btmbutPanel.add(ExecBut);

		fullPanel.add(topGridPanel, BorderLayout.NORTH);
		fullPanel.add(midGridPanel, BorderLayout.CENTER);
		fullPanel.add(btmbutPanel, BorderLayout.SOUTH);

		exp_d.getContentPane().add(fullPanel, BorderLayout.NORTH);
		exp_d.toFront ();
		exp_d.pack();
		exp_d.show();
	}

	public void actionPerformed( ActionEvent evt ) {
		Object source = evt.getSource();

		if ( source == probj_but ) {
			dap_fc.addChoosableFileFilter( dap_filter );
			dap_fc.setMultiSelectionEnabled(true);
			int returnVal = dap_fc.showOpenDialog( exp_d );

            if (returnVal == JFileChooser.APPROVE_OPTION) {
				selectedFiles = dap_fc.getSelectedFiles();

				for (int i = 0; i < selectedFiles.length; i++) {
					probjTA.append( selectedFiles[i].getPath() + "\n" );
				}
			} else {}
		}
		else if ( source == exp_obj_but ) {
			exptypeStg	= getexptype();
			String addbatchStg = "";
			for (int z = 0; z < selectedFiles.length; z++) {
				addbatchStg = exptypeStg + " || " + selectedFiles[z].getPath();
				probj2exp.append( addbatchStg + "\n" );
			}
		}
		else if ( source == outpath_but ) {
			dir_out_fc.addChoosableFileFilter( dir_filter );
			dir_out_fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
			int returnVal = dir_out_fc.showOpenDialog( exp_d );

            if (returnVal == JFileChooser.APPROVE_OPTION) {
				exp_out_DIR	=	dir_out_fc.getCurrentDirectory()
								+ java.io.File.separator
								+ dir_out_fc.getSelectedFile().getName();
				outpathField.setText(exp_out_DIR);
            } else {}
		}
		else if ( source == defdir_but ) {
			usr_ws_fc.addChoosableFileFilter( dir_filter );
			usr_ws_fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
			int returnVal = usr_ws_fc.showOpenDialog( exp_d );

            if (returnVal == JFileChooser.APPROVE_OPTION) {
				curdefdir =	usr_ws_fc.getCurrentDirectory()
							+ java.io.File.separator
							+ usr_ws_fc.getSelectedFile().getName();
				defdirField.setText(curdefdir);
				dap_fc = new JFileChooser(curdefdir);
            } else {}
		}
	}

	public String getexptype() {
		exptypeStg = exptypeField.getText();
		return exptypeStg;
	}

	public String getexpout() {
		exp_out_DIR = outpathField.getText();
		return exp_out_DIR;
	}

	public void SaveSelected( String exp_txtnm, String full_proe_bat ) {
		String finStg = put_batcont();

		try {
			PrintStream expfl = new PrintStream(new FileOutputStream(exp_txtnm));
			expfl.println( finStg );
			expfl.flush();
			expfl.close();
		} catch(java.io.IOException IOEx) {
			System.out.println("Cannot create " + exp_txtnm + " file.");
		}
	}

	public void SaveSelectedBat( String bat_cmd, String dxf_exp_form, String call_exp_batnm ) {
		exp_out_DIR	= getexpout();
		//dxf_exp_form = getdxfform();
		System.out.println( "dxf_exp_form: " + dxf_exp_form );
		try {
			PrintStream expfl = new PrintStream(new FileOutputStream(call_exp_batnm));
			expfl.println( "cd \\\n" );
			//expfl.println( "dxf_export_format " + dxf_exp_form + "\n" );
			expfl.println( "cd " + exp_out_DIR + "\n" );
			expfl.println( bat_cmd );
			expfl.println( "pause" );
			expfl.flush();
			expfl.close();
		} catch(java.io.IOException IOEx) { System.out.println("Cannot create " + call_exp_batnm + " file."); }
	}

	public String put_batcont() {
		String expcontStg = probj2exp.getText().trim();;
		String expcontStg1 = StgReplace(expcontStg,"DXF", "-dxf -object" );
		String expcontStg2 = StgReplace(expcontStg1,"IGES", "-iges -object" );
		String expcontStg3 = StgReplace(expcontStg2,"VRML", "-vrml -object" );
		String expcontStg4 = StgReplace(expcontStg3,"STEP", "-step -object" );
		String expcontStgfin = StgReplace(expcontStg4," || ", " " );

		return expcontStgfin;
	}

	public void RunCmdInt ( String call_exp_batnm ) {

		String s = null;
		try {
			Process p = Runtime.getRuntime().exec("cmd /c " + call_exp_batnm );
			BufferedReader stdInput = new BufferedReader(new
				InputStreamReader(p.getInputStream()));

			BufferedReader stdError = new BufferedReader(new
				InputStreamReader(p.getErrorStream()));

			while ((s = stdInput.readLine()) != null) {
				System.out.println( s );}

			while ((s = stdError.readLine()) != null) {
				System.out.println("Standard Error: " + s + "\n");}

			System.out.println("All Exporting Completed.\n");
			System.exit(0);
		}
		catch (IOException e) {
			System.out.println("Exception: ");
			e.printStackTrace();
			System.exit(-1);
		}
	}

	public static String StgReplace (String target, String from, String to) {
		int start = target.indexOf (from);
		if (start==-1) return target;
		int lf = from.length();
		int tf = target.length();
		char [] targetChars = target.toCharArray();
		StringBuffer buffer = new StringBuffer();
		int copyFrom=0;
		while (start != -1)
		{
			buffer.append (targetChars, copyFrom, start-copyFrom);
			buffer.append (to);
			copyFrom=start+lf;
			start = target.indexOf (from, copyFrom);
		}
		buffer.append (targetChars, copyFrom, targetChars.length-copyFrom);
		String finstg = buffer.toString();

		return finstg;
	}

	public static void main(String[] args) {
		Exp_Out exp_d;
		exp_d = new Exp_Out();

		exp_d.addWindowListener( new WindowAdapter() {
			public void windowClosing( WindowEvent e ) { System.exit(0); }
		});
	}
}
