/* $Id: GSHTMLRuntimeEditor.java 217 2011-06-10 00:53:06Z ohura $ */
package com.hexidec.ekit;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.concurrent.atomic.AtomicLong;

import javax.swing.JOptionPane;
import javax.swing.JTextArea;

import smart_gs.logical.Preference;
import smart_gs.swingui.WorkspaceWindow;

public class GSHTMLRuntimeEditor implements ActionListener{
	protected JTextArea jtpSource;
	protected AtomicLong counter = new AtomicLong();
	protected SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
	
	public GSHTMLRuntimeEditor(JTextArea jtpSource){
		this.jtpSource = jtpSource;
	}
	
	public void actionPerformed(ActionEvent e) {
		counter.incrementAndGet();
		Thread thread = new Thread(new EditThread());
		thread.start();
	}

	class EditThread implements Runnable{
		protected File tempFile;
		public void run() {
			File fileCurrent=new File(".");
			DecimalFormat df = new DecimalFormat("0000000");
			Calendar cal = Calendar.getInstance();
			tempFile = new File(fileCurrent.getAbsolutePath() + "/temp/" + sdf.format(cal.getTime()) + df.format(counter.longValue()) + ".html");

			FileOutputStream fos = null;
			try{
				fos = new FileOutputStream(tempFile.getAbsolutePath());
				synchronized (jtpSource) {
					fos.write(jtpSource.getText().getBytes());
				}
				fos.flush();
			}catch(IOException e){
				e.printStackTrace();
				// 書き出し失敗
				return;
			}finally{
				if(fos != null){
					try {
						fos.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			String editor = Preference.getInstance().getEditor();
			if(editor == null){
				JOptionPane.showMessageDialog(WorkspaceWindow.getInstance(),"The editor is not settting. ","Error",JOptionPane.ERROR_MESSAGE);
				return;
			}
			ProcessBuilder pb = new ProcessBuilder(editor, tempFile.getAbsolutePath());
		    try {
		    	long modified = tempFile.lastModified();
		        Process p = pb.start();
		        int ret = p.waitFor();
		        synchronized (jtpSource) {
		        	if(modified != tempFile.lastModified()){
			        	FileInputStream in = new FileInputStream(tempFile.getAbsolutePath());
			        	ByteArrayOutputStream baos = new ByteArrayOutputStream();
			            byte[] buffer = new byte[8192];
			            int rsize;
			            while ((rsize = in.read(buffer)) != -1) {
			            	baos.write(buffer,0,rsize);
			            }
			            int yesno = JOptionPane.showConfirmDialog(WorkspaceWindow.getInstance(),"The file was modefied by the external editor that you invoked.\r\nDo you like to reload the file edited on the disk?","Reload confirmation",JOptionPane.YES_NO_OPTION);
						if(yesno==0){
							jtpSource.setText(new String(baos.toByteArray()));
						}
						in.close();
		        	}
		        }
		    } catch (IOException ex) {
		    	ex.printStackTrace();
		    } catch (InterruptedException ex) {
		    	ex.printStackTrace();
		    }finally{
		    	tempFile.delete();
		    }
			
		}
		
	}
	
}
