//------------------------------------------------------------------------------
// Copyright (c) 2005, 2006 IBM Corporation and others.
// 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:
// IBM Corporation - initial implementation
//------------------------------------------------------------------------------
package org.eclipse.epf.authoring.ui.forms;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;

import org.eclipse.epf.authoring.ui.AuthoringUIPlugin;
import org.eclipse.epf.authoring.ui.AuthoringUIResources;
import org.eclipse.epf.authoring.ui.AuthoringUIText;
import org.eclipse.epf.authoring.ui.editors.MethodElementEditor;
import org.eclipse.epf.library.LibraryService;
import org.eclipse.epf.library.edit.command.IActionManager;
import org.eclipse.epf.library.edit.util.TngUtil;
import org.eclipse.epf.library.util.ResourceHelper;
import org.eclipse.epf.uma.ContentDescription;
import org.eclipse.epf.uma.UmaPackage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.List;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.forms.editor.FormEditor;
import org.eclipse.ui.forms.widgets.FormToolkit;


/**
 * The Description page in a Template editor.
 * 
 * @author Shashidhar Kannoori
 * @author Kelvin Low
 * @since 1.0
 */
public class TemplateDescriptionPage extends GuidanceDescriptionPage {

	private Button ctrl_attach, ctrl_detach; // , ctrl_remove;

	private List ctrl_template_file;

	private static final String TEMPLATE_ATTACHMENT_LAST_DIRECTORY_BROWSED_PREF = "template_attachment_last_dir_browsed"; //$NON-NLS-1$

	/**
	 * Creates a new instance.
	 */
	public TemplateDescriptionPage(FormEditor editor) {
		super(editor);
	}

	protected void createEditorContent(FormToolkit toolkit) {
		super.createEditorContent(toolkit);

		createLabel(toolkit, generalComposite,
				AuthoringUIText.TEMPLATE_FILE_TEXT, 2);
		ctrl_template_file = new List(generalComposite, SWT.SINGLE
				| SWT.V_SCROLL | SWT.H_SCROLL);
		GridData listGridData = new GridData(SWT.BEGINNING, SWT.BEGINNING,
				true, true);
		listGridData.heightHint = 30;
		listGridData.widthHint = 300;
		ctrl_template_file.setLayoutData(listGridData);

		ctrl_template_file.setData(FormToolkit.KEY_DRAW_BORDER,
				FormToolkit.TEXT_BORDER);

		Composite buttonComposite = createComposite(toolkit, generalComposite,
				1);
		GridData gridData = new GridData(GridData.HORIZONTAL_ALIGN_END);
		gridData.verticalSpan = 1;
		gridData.horizontalSpan = 3;
		buttonComposite.setLayoutData(gridData);
		buttonComposite.setLayout(new GridLayout(3, false));

		ctrl_attach = createButton(toolkit, buttonComposite, ATTACH_BUTTON);
		ctrl_detach = createButton(toolkit, buttonComposite, DETACH_BUTTON);
		// ctrl_remove = createButton(toolkit, buttonComposite, REMOVE_BUTTON);

		label_base.setText(AuthoringUIText.BASE_GUIDANCE_TEXT);

	}

	/**
	 * Add focus listeners
	 * 
	 */
	protected void addListeners() {
		super.addListeners();

		final IActionManager actionMgr = ((MethodElementEditor) getEditor())
				.getActionManager();

		ctrl_attach.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				FileDialog dialog = new FileDialog(PlatformUI.getWorkbench()
						.getActiveWorkbenchWindow().getShell());
				dialog
						.setText(AuthoringUIResources.attachTemplateFileDialog_title); //$NON-NLS-1$
				String lastDir = AuthoringUIPlugin
						.getDefault()
						.getPreferenceStore()
						.getString(
								TEMPLATE_ATTACHMENT_LAST_DIRECTORY_BROWSED_PREF);
				if (lastDir != null && lastDir.trim().length() > 0) {
					dialog.setFilterPath(lastDir);
				} else {
					dialog.setFilterPath(LibraryService.getInstance()
							.getCurrentMethodLibraryPath()
							+ File.separator
							+ ResourceHelper.getElementPath(guidance));
				}
				dialog.open();
				if (dialog.getFileName() != null && dialog.getFileName() != "") { //$NON-NLS-1$
					try {
						File fileToAttach = new File(dialog.getFilterPath(),
								dialog.getFileName());
						String fileUrl = ResourceHelper.getURLForAttachment(
								fileToAttach, guidance, true);
						if (ctrl_template_file.indexOf(fileUrl) != -1) {
							// file is already an attachment
							AuthoringUIPlugin
									.getDefault()
									.getMsgDialog()
									.displayInfo(
											AuthoringUIResources.AttachmentDialogattachFile_text, //$NON-NLS-1$ 
											AuthoringUIResources.forms_TemplateDescriptionPage_alreadyAttached_msg); //$NON-NLS-1$
							return;
						}
						ctrl_template_file.add(fileUrl);
						boolean status = actionMgr.doAction(IActionManager.SET,
								guidance.getPresentation(),
								UmaPackage.eINSTANCE
										.getGuidanceDescription_Attachments(),
								getFilesFromListCtrl(), -1);
						if (!status) {
							return;
						} else {
							AuthoringUIPlugin
									.getDefault()
									.getPreferenceStore()
									.setValue(
											TEMPLATE_ATTACHMENT_LAST_DIRECTORY_BROWSED_PREF,
											dialog.getFilterPath());
						}
					} catch (IOException ex) {
						// TODO: Display an error dialog.
						ex.printStackTrace();
					}
				}
			}
		});

		ctrl_detach.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				ctrl_template_file.remove(ctrl_template_file
						.getSelectionIndex());
				boolean status = actionMgr.doAction(IActionManager.SET,
						guidance.getPresentation(), UmaPackage.eINSTANCE
								.getGuidanceDescription_Attachments(),
						getFilesFromListCtrl(), -1);

				if (!status) {
					// ctrl_template_file.setText(oldContent);
					return;
				}
			}
		});

		// ctrl_remove.addSelectionListener(new SelectionAdapter(){
		// public void widgetSelected(SelectionEvent e) {
		// //ctrl_template_file.setText(""); //$NON-NLS-1$
		// String oldContent =
		// ((GuidanceDescription)guidance.getPresentation()).getAttachments();
		// ctrl_template_file.setText(""); //$NON-NLS-1$
		// boolean status = actionMgr.doAction(IActionManager.SET,
		// guidance.getPresentation(),
		// UmaPackage.eINSTANCE.getGuidanceDescription_Attachments(),
		// ctrl_template_file.getText(), -1);
		// if(!status){
		// //ctrl_template_file.setText(oldContent);
		// return;
		// }
		// }
		// });
	}

	protected void refresh(boolean editable) {
		super.refresh(editable);
		ctrl_attach.setEnabled(editable);
		ctrl_detach.setEnabled(editable);
		// ctrl_remove.setEnabled(editable);
	}

	/**
	 * Load initial data from model
	 */
	protected void loadData() {
		super.loadData();
		if (guidance != null) {
			ContentDescription content = (ContentDescription) guidance
					.getPresentation();
			String thirdpartyformat = ((org.eclipse.epf.uma.GuidanceDescription) content)
					.getAttachments();
			setFilesToListCtrl(thirdpartyformat);
		}
	}

	protected Object getContentElement() {
		return contentElement;
	}

	/**
	 * Given a string of files, add the files to the List control
	 * 
	 * @param files
	 */
	private void setFilesToListCtrl(String fileString) {
		java.util.List attachmentList = TngUtil
				.convertTemplateAttachmentsToList(fileString);
		ctrl_template_file.removeAll();

		for (Iterator iter = attachmentList.iterator(); iter.hasNext();) {
			String attachment = (String) iter.next();
			ctrl_template_file.add(attachment);

		}
	}

	/**
	 * returns the list of files as a string
	 * 
	 * @return
	 */
	private String getFilesFromListCtrl() {
		String files[] = ctrl_template_file.getItems();
		return TngUtil.convertTemplateAttachmentsToString(Arrays.asList(files));
	}

}