/*
 * Created on 15.06.2004
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 */
package networkconsole.datamodel.swt.dialogs;

import java.io.File;
import java.util.Properties;
import java.util.ResourceBundle;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;


import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;

/**
 * @author Eugene Prokopiev <john@rmts.donpac.ru>
 * 
 */
public class ExportDialog extends Dialog {

	private FileText fileText;	
	private FileText appText;
	private Combo styleCombo;
	private Button appCheck;
	private Button styleCheck;
	
	private SAXSource source;
	private Properties properties;
	
	public ExportDialog(Shell parent, SAXSource source, Properties properties) {
		super(parent);
		this.source = source;
		this.properties = properties;
	}
	
	protected Control createDialogArea(Composite parent) {
		Composite area = (Composite) super.createDialogArea(parent);
		Composite container = new Composite(area, SWT.NONE);
		container.setLayout(new FormLayout());
		GridData gridData = new GridData(GridData.FILL_BOTH);
		gridData.widthHint = 400;
		container.setLayoutData(gridData);
		{
			final Composite composite = new Composite(container, SWT.NONE);
			composite.setLayout(new GridLayout());
			final FormData formData = new FormData();
			formData.bottom = new FormAttachment(100, 5);
			formData.right = new FormAttachment(100, 5);
			formData.top = new FormAttachment(0, -5);
			formData.left = new FormAttachment(0, -5);
			composite.setLayoutData(formData);
			{
				final Group group = new Group(composite, SWT.NONE);
				group.setLayoutData(new GridData(GridData.FILL_BOTH));
				final GridLayout gridLayout = new GridLayout();
				gridLayout.marginWidth = 7;
				gridLayout.marginHeight = 7;
				gridLayout.horizontalSpacing = 15;
				group.setLayout(gridLayout);									
				{
					final Label label = new Label(group, SWT.NONE);
					label.setText(translate("ui.dialog.export.label.file"));
				}
				{
					fileText = new FileText(group, SWT.NONE);
					fileText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));	
					fileText.setText(makeFileName());				
				}
				{
					styleCheck = new Button(group, SWT.CHECK);
					styleCheck.setText(translate("ui.dialog.export.label.style"));
					styleCheck.addSelectionListener(new SelectionAdapter() {
						public void widgetSelected(SelectionEvent e) {
							setStyleCheck(styleCheck.getSelection());
						}						
					});
				}
				{
					styleCombo = new Combo(group, SWT.NONE);
					styleCombo.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
					styleCombo.setEnabled(styleCheck.getSelection());
					styleCombo.setItems(makeXsltFileNames());
					if (styleCombo.getItemCount() > 0)
						styleCombo.setText(styleCombo.getItem(0));
					boolean checked = properties.getProperty("export.apply.xslt").equals("true");
					styleCheck.setSelection(checked);
					setStyleCheck(checked);
				}
				{
					appCheck = new Button(group, SWT.CHECK);
					appCheck.setText(translate("ui.dialog.export.label.application"));
					appCheck.addSelectionListener(new SelectionAdapter() {
						public void widgetSelected(SelectionEvent e) {
							setAppCheck(appCheck.getSelection());
						}
					});
				}
				{
					appText = new FileText(group, SWT.NONE);
					appText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
					appText.setEnabled(appCheck.getSelection());	
					appText.setText(properties.getProperty("export.path.application"));	
					boolean checked = properties.getProperty("export.apply.application").equals("true");
					appCheck.setSelection(checked);	
					setAppCheck(checked);
				}
			}
		}
		
		return area;
	}
	
	protected void createButtonsForButtonBar(Composite parent) {
		
		createButton(
			parent,
			IDialogConstants.OK_ID,
			translate("ui.dialog.ok"),
			true);
			
		createButton(
			parent,
			IDialogConstants.CANCEL_ID,
			translate("ui.dialog.cancel"),
			false);
	}
	
	protected void okPressed() {
		try {			
			exportData();
			openData();	
			saveSettings();
		} catch (Exception e) {
			MessageDialog.openError(getShell(), getShell().getText(), 
				"["+e.getClass().getName()+"] "+e.getLocalizedMessage());
			e.printStackTrace();
		}	
		super.okPressed();			
	}

	private void exportData() throws Exception {
		TransformerFactory factory = TransformerFactory.newInstance();
		Transformer transformer;	
		if (styleCheck.getSelection())		
			transformer = factory.newTransformer(new StreamSource(
				properties.getProperty("export.path.xslt")+
				File.separator+styleCombo.getText()));	
		else
			transformer = factory.newTransformer();
		transformer.setOutputProperty(OutputKeys.ENCODING, properties.getProperty("export.encoding"));			
		transformer.transform(source, new StreamResult(fileText.getText()));
	}
	
	private void openData() throws Exception {
		if (appCheck.getSelection())
			Runtime.getRuntime().exec(appText.getText()+" "+fileText.getText());
	}

	private void saveSettings() throws Exception {
		properties.setProperty("export.path.application", appText.getText());
		properties.setProperty("export.apply.application", (appCheck.getSelection())?("true"):("false"));
		properties.setProperty("export.apply.xslt", (styleCheck.getSelection())?("true"):("false"));		
	}
	
	protected void configureShell(Shell shell) {		
		super.configureShell(shell);
		shell.setText(translate("ui.dialog.export.caption"));
	}
	
	private String makeFileName() {
		return properties.getProperty("export.path.file")+File.separator+"filename.xml";
	}
	
	private String[] makeXsltFileNames() {
		return new File(properties.getProperty("export.path.xslt")).list();
	}
	
	private void setStyleCheck(boolean checked) {
		styleCombo.setEnabled(checked);
		if (checked)
			fileText.setText(fileText.getText().replaceAll("xml", "html"));
		else
			fileText.setText(fileText.getText().replaceAll("html", "xml"));
	}
	
	private void setAppCheck(boolean checked) {
		appText.setEnabled(checked);
	}
	
	public static String translate(String element) {
		return ResourceBundle.getBundle("networkconsole/datamodel/swt/dialogs/translation").getString(element);
	}
}
