/*
 * Copyright (C) 2005 NTT DATA Corporation
 * 
 */
package org.postgresforest.tool.view.action;


import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.eclipse.jface.action.IAction;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.PlatformUI;
import org.postgresforest.tool.view.ddl.DdlView;

/**
 *
 * ClearDdlAction
 * @version $Revision: 1.1.1.1 $
 * @since 
 */
public class ReadDdlAction extends ActionBase {
	public void init(IViewPart view) {
		super.init(view);
		

	}
	/* (non-Javadoc)
	 * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
	 */
	public void run(IAction action) {
		Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
		FileDialog dialog = new FileDialog(shell, SWT.OPEN);
		String file = dialog.open();
		String ddlString = "";
		if((file != "") && (file != null)){
			if(m_view instanceof DdlView ){
				DdlView ddlView = (DdlView)m_view;
				
				try{
					ddlString = getFileToString(file);
				}catch(Exception e){
					//TODOMASU Exceptionはどうやって処理する？
					e.printStackTrace();
				}
				ddlView.setDdl(ddlView.getDdl() + ddlString);
			}	
		}
	}
	private String getFileToString(String fileName) throws FileNotFoundException, IOException {
		byte[] buf = new byte[64];
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		FileInputStream in = new FileInputStream(fileName);
		String retString = "";
		int nBytes;
		
		
		while ((nBytes = in.read(buf)) > 0){
			out.write(buf, 0, nBytes);
		}

		in.close();
		
		retString = out.toString();
		out.close();
		return retString;
	}
}
