/*
 * Copyright (c) 2006-2008 Maskat Project.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Maskat Project - initial API and implementation
 */
package org.maskat.ui.wizards.export;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IExportWizard;
import org.eclipse.ui.IWorkbench;
import org.maskat.core.betwixt.MessageSchemaGenerator;
import org.maskat.core.event.Param;
import org.maskat.core.event.Result;
import org.maskat.ui.MaskatUIPlugin;
import org.maskat.ui.Messages;

public class ExportMessageSchemaWizard extends Wizard implements IExportWizard {

	private IStructuredSelection selection;
	
	private ExportMessageSchemaWizardPage page;
	
	public void init(IWorkbench workbench, IStructuredSelection selection) {
		this.selection = selection;
	}

	public void addPages() {
		IResource selectedElement = null;
		if (this.selection != null) {
			Object select = this.selection.getFirstElement();
			if (select instanceof IResource) {
				selectedElement = (IResource) select;
			}
		}
		page = new ExportMessageSchemaWizardPage(selectedElement);
		setWindowTitle(Messages.getString("exportSchemaWizard.windowtitle")); //$NON-NLS-1$
		addPage(page);
	}
	
	public boolean performFinish() {
		ExportMessage[] msg = page.getSelectedMessages();
		IPath outPath = page.getOutputFilePath();
		String baseDir = outPath.toFile().getAbsolutePath();
		byte[] buffer = new byte[2048];
		
		for (int i = 0; i < msg.length; i++) {
			InputStream in = null;
			OutputStream out = null;
			String cmpName = msg[i].getComponentName();
			if (cmpName == null) {
				cmpName = "root"; //$NON-NLS-1$
			}
			StringBuffer sb = new StringBuffer(baseDir);
			sb.append("/"); //$NON-NLS-1$
			sb.append(cmpName);
			File dir = new File(sb.toString());
			dir.mkdirs();
			
			try {
				
				if (msg[i].getType() == ExportMessage.REQUEST) {
					in = MessageSchemaGenerator.generateRequestXMLSchema(
							(Param) msg[i].getElement());
				} else {
					in = MessageSchemaGenerator.generateResponseXMLSchema(
							(Result) msg[i].getElement());
				}
				File directory = new File(dir.getPath());
				File saveFile = new File(directory, msg[i].getFileName());
				
				if (saveFile.exists() && !saveFile.canWrite()) {
				    MessageDialog.openError(Display.getCurrent().getActiveShell(),
				    		Messages.getString("exportSchemaWizard.msg.error.title"), //$NON-NLS-1$
				    		Messages.getString("exportSchemaWizard.msg.error.notwrite")); //$NON-NLS-1$
				    break;
				}
				out = new BufferedOutputStream(new FileOutputStream(saveFile));
				
				int cnt;
				while ((cnt = in.read(buffer)) != -1) {
					out.write(buffer, 0, cnt);
				}
								
			} catch (Exception e) {
				MaskatUIPlugin.log(new Status(IStatus.ERROR,
						MaskatUIPlugin.PLUGIN_ID, IStatus.ERROR, e
								.getMessage(), e));
				
			    MessageDialog.openError(Display.getCurrent().getActiveShell(),
			    		Messages.getString("exportSchemaWizard.msg.error.title"), //$NON-NLS-1$
			    		Messages.getString("exportSchemaWizard.msg.error.notwrite")); //$NON-NLS-1$
			    
				return false;
				
			} finally {
				try {
					if (in != null) {
						in.close();
					}
					if (out != null) {
						out.close();
					}
				} catch (IOException ex) {}
			}
		}
		return true;
	}

}
