/**
 *#########################################################################
 *
 * A component of the Gatherer application, part of the Greenstone digital
 * library suite from the New Zealand Digital Library Project at the
 * University of Waikato, New Zealand.
 *
 * Author: John Thompson, Greenstone Digital Library, University of Waikato
 *
 * Copyright (C) 1999 New Zealand Digital Library Project
 *
 * 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.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *########################################################################
 */
package org.greenstone.gatherer.cdm;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.regex.*;
import javax.swing.*;
import javax.swing.filechooser.*;
import javax.swing.event.*;
import org.greenstone.gatherer.Configuration;
import org.greenstone.gatherer.DebugStream;
import org.greenstone.gatherer.Dictionary;
import org.greenstone.gatherer.Gatherer;
import org.greenstone.gatherer.collection.CollectionManager;
import org.greenstone.gatherer.gui.DesignPaneHeader;
import org.greenstone.gatherer.gui.EmailField;
import org.greenstone.gatherer.gui.GLIButton;
import org.greenstone.gatherer.gui.GUIUtils;
import org.greenstone.gatherer.gui.TestingPreparation;
import org.greenstone.gatherer.remote.RemoteGreenstoneServer;
import org.greenstone.gatherer.util.StaticStrings;
import org.greenstone.gatherer.Gatherer;

/** This class provides a graphical interface for editing general metadata for the collection, such as name, description, icons etc. 
*/
public class GeneralManager {

    /** The controls used to modify the general options. */
    private Control controls;
    /** Constructor. */
    public GeneralManager() {
    }

    /** Destructor. */
    public void destroy() {
	if (controls != null) {
	    controls.destroy();
	    controls = null;
	}
    }

    public void loseFocus() {
    }

    public void gainFocus() {

    }
    /** This class is resposible for generating the controls for the editing of general options.
     * @return the Control for editing the general options
     */
    public Control getControls() {
	if (controls == null) {
	    controls = new GeneralControl();
	}
	return controls;
    }
    

    /** Called when the detail mode has changed which in turn may cause several design elements to be available/hidden
     * @param mode the new mode as an int
     */
    public void modeChanged(int mode) {

    }
    
    /** This class represents the visual component of the general options stored in the CollectionDesignManager. */
    private class GeneralControl
	extends JPanel
	implements Control {

        private boolean ready = false;
	private CollectionMeta collection_extra_collectionmeta;
	private CollectionMeta collection_name_collectionmeta;
	private CollectionMeta creator_collectionmeta;
	private CollectionMeta icon_collection_collectionmeta;
	private CollectionMeta icon_collection_small_collectionmeta;
	private CollectionMeta maintainer_collectionmeta;
	private CollectionMeta public_collectionmeta;
	/** The creators email. */
	private EmailField creator_emailfield;
	/** The maintainers email. */
	private EmailField maintainer_emailfield;
	/** Button to browse for the collection about page icon. */
	private JButton browse_about_icon_button;
	/** Button to browse for the collection home page icon. */
	private JButton browse_home_icon_button;
	/** The checkbox controlling public access to the collection. */
	private JCheckBox public_checkbox;
	private JLabel creator_label;
	private JLabel description_label;
	private JLabel icon_label;
	private JLabel maintainer_label;
	private JLabel name_label;
	private JLabel small_icon_label;
	/** The text field used to edit the file name of the collections icon. */
	private JTextField icon_textfield;
	/** The text field used to edit the collections title. */
	private JTextField name_textfield;
	/** The text field used to edit the file name of the collections small icon. */
	private JTextField small_icon_textfield;
	/** A text area used to modify the collection description. */
	private JTextArea description_textarea;
	/** Constructor. */
	public GeneralControl() {
	    super();
            this.setComponentOrientation(Dictionary.getOrientation());
	    // Retrieve some of the model elements, those we know aren't language dependant
	    public_collectionmeta = new CollectionMeta(CollectionDesignManager.collect_config.getPublic());

	    // Creation
	    JPanel header_panel = new DesignPaneHeader("CDM.GUI.General", "generalsettings");
            
	    JPanel all_details_panel = new JPanel();
	    JPanel details_panel = new JPanel();
	    JPanel fields_panel = new JPanel();

            all_details_panel.setComponentOrientation(Dictionary.getOrientation());
            details_panel.setComponentOrientation(Dictionary.getOrientation());
            fields_panel.setComponentOrientation(Dictionary.getOrientation());
                        
	    creator_label = new JLabel(Dictionary.get("CDM.General.Email.Creator"));
	    creator_label.setComponentOrientation(Dictionary.getOrientation());
            
	    creator_emailfield = new EmailField(Configuration.getColor("coloring.error_background", false));
	    creator_emailfield.setToolTipText(Dictionary.get("CDM.General.Email.Creator_Tooltip"));
	    
	    maintainer_label = new JLabel(Dictionary.get("CDM.General.Email.Maintainer"));
	    maintainer_label.setComponentOrientation(Dictionary.getOrientation());
            
	    maintainer_emailfield = new EmailField(Configuration.getColor("coloring.error_background", false));
	    maintainer_emailfield.setToolTipText(Dictionary.get("CDM.General.Email.Maintainer_Tooltip"));
	    
	    name_label = new JLabel(Dictionary.get("CDM.General.Collection_Name"));
            name_label.setComponentOrientation(Dictionary.getOrientation());
	    name_textfield = new JTextField();
            name_textfield.setComponentOrientation(Dictionary.getOrientation());
	    name_textfield.setToolTipText(Dictionary.get("CDM.General.Collection_Name_Tooltip"));
	    
	    JLabel short_name_label = new JLabel(Dictionary.get("NewCollectionPrompt.Collection_Name"));
	    short_name_label.setComponentOrientation(Dictionary.getOrientation());
            JTextField short_name_textfield = new JTextField(CollectionManager.getLoadedCollectionName());
            short_name_textfield.setComponentOrientation(Dictionary.getOrientation());
	    short_name_textfield.setEditable(false);
	    short_name_textfield.setBackground(Configuration.getColor("coloring.collection_tree_background", false));
	    JPanel icon_panel = new JPanel();
            icon_panel.setComponentOrientation(Dictionary.getOrientation());
	    icon_label = new JLabel(Dictionary.get("CDM.General.Icon_Collection"));
            icon_label.setComponentOrientation(Dictionary.getOrientation());
	    icon_textfield = new JTextField();
            icon_textfield.setComponentOrientation(Dictionary.getOrientation());
	    icon_textfield.setToolTipText(Dictionary.get("CDM.General.Icon_Collection_Tooltip")); 
	    browse_about_icon_button = new GLIButton(Dictionary.get("General.Browse"));
	    JPanel small_icon_panel = new JPanel();
            small_icon_panel.setComponentOrientation(Dictionary.getOrientation());
	    small_icon_label = new JLabel(Dictionary.get("CDM.General.Icon_Collection_Small"));
            small_icon_label.setComponentOrientation(Dictionary.getOrientation());
	    small_icon_textfield = new JTextField();
            small_icon_textfield.setComponentOrientation(Dictionary.getOrientation());
	    small_icon_textfield.setToolTipText(Dictionary.get("CDM.General.Icon_Collection_Small_Tooltip"));
	    browse_home_icon_button = new GLIButton(Dictionary.get("General.Browse"));

	    // public
	    JPanel box_panel = new JPanel();
            box_panel.setComponentOrientation(Dictionary.getOrientation());
	    public_checkbox = new JCheckBox(Dictionary.get("CDM.General.Access"), public_collectionmeta.getValue(CollectionMeta.TEXT).equals(StaticStrings.TRUE_STR));
	    public_checkbox.setComponentOrientation(Dictionary.getOrientation());
            
	    JPanel description_panel = new JPanel();
            description_panel.setComponentOrientation(Dictionary.getOrientation());
	    description_label = new JLabel(Dictionary.get("CDM.General.Collection_Extra"));
	    description_label.setComponentOrientation(Dictionary.getOrientation());
            
	    description_textarea = new JTextArea();
            description_textarea.setComponentOrientation(Dictionary.getOrientation());
	    description_textarea.setBackground(Configuration.getColor("coloring.editable_background", false));
	    description_textarea.setToolTipText(Dictionary.get("CDM.General.Collection_Extra_Tooltip"));
	    
	    // Connection
	    BrowseListener browse_listener = new BrowseListener(StaticStrings.IMAGES_PATH_RELATIVE_TO_GSDL_PREFIX);
	    browse_about_icon_button.addActionListener(browse_listener);
	    browse_home_icon_button.addActionListener(browse_listener);
	    browse_listener = null;
	    public_checkbox.addActionListener(CollectionDesignManager.change_listener);
	    creator_emailfield.getDocument().addDocumentListener(CollectionDesignManager.change_listener);
	    description_textarea.getDocument().addDocumentListener(CollectionDesignManager.change_listener);
	    icon_textfield.getDocument().addDocumentListener(CollectionDesignManager.change_listener);
	    maintainer_emailfield.getDocument().addDocumentListener(CollectionDesignManager.change_listener);
	    name_textfield.getDocument().addDocumentListener(CollectionDesignManager.change_listener);
	    name_textfield.getDocument().addDocumentListener(new CollectionTitleUpdater());
	    small_icon_textfield.getDocument().addDocumentListener(CollectionDesignManager.change_listener);

	    // Layout
	    fields_panel.setBorder(BorderFactory.createEmptyBorder(5,0,0,0));
	    fields_panel.setLayout(new BorderLayout(5,2));
	    
	    JPanel fields_label_panel = new JPanel();
            fields_label_panel.setComponentOrientation(Dictionary.getOrientation());
	    fields_label_panel.setLayout(new GridLayout(6,1));

	    JPanel fields_box_panel = new JPanel();
            fields_box_panel.setComponentOrientation(Dictionary.getOrientation());            
	    fields_box_panel.setLayout(new GridLayout(6,1));
    
	    // creator
	    fields_label_panel.add(creator_label);
	    fields_box_panel.add(creator_emailfield);

	    // maintainer
	    fields_label_panel.add(maintainer_label);
	    fields_box_panel.add(maintainer_emailfield);

	    // title
	    fields_label_panel.add(name_label);
	    fields_box_panel.add(name_textfield);

	    // collection short name
	    fields_label_panel.add(short_name_label);
	    fields_box_panel.add(short_name_textfield);

	    // icon
	    fields_label_panel.add(icon_label);
	    fields_box_panel.add(icon_panel);

	    // small icon
	    fields_label_panel.add(small_icon_label);
	    fields_box_panel.add(small_icon_panel);

	    fields_panel.add(fields_label_panel, BorderLayout.LINE_START);
	    fields_panel.add(fields_box_panel, BorderLayout.CENTER);

	    icon_panel.setLayout(new BorderLayout());
	    icon_panel.add(icon_textfield, BorderLayout.CENTER);
	    icon_panel.add(browse_about_icon_button, BorderLayout.LINE_END);

	    small_icon_panel.setLayout(new BorderLayout());
	    small_icon_panel.add(small_icon_textfield, BorderLayout.CENTER);
	    small_icon_panel.add(browse_home_icon_button, BorderLayout.LINE_END);

	    box_panel.setLayout(new GridLayout(1,1,5,2));
	    box_panel.add(public_checkbox);

	    description_panel.setLayout(new BorderLayout());
	    description_panel.add(description_label, BorderLayout.NORTH);
	    description_panel.add(new JScrollPane(description_textarea), BorderLayout.CENTER);
	    
	    details_panel.setLayout(new BorderLayout());
	    details_panel.add(fields_panel, BorderLayout.NORTH);
	    details_panel.add(box_panel, BorderLayout.CENTER);

	    all_details_panel.setLayout(new BorderLayout());
	    all_details_panel.add(details_panel, BorderLayout.NORTH);
	    all_details_panel.add(description_panel, BorderLayout.CENTER);

	    setBorder(BorderFactory.createEmptyBorder(0,5,0,0));
	    setLayout(new BorderLayout());
	    add(header_panel, BorderLayout.NORTH);
	    add(all_details_panel, BorderLayout.CENTER);

	    // Setting custom names on select widgets to avoid naming collisions,
	    // as default names are based on type and both are checkboxes.
	    TestingPreparation.setIndividualSubcomponentNames(this,
							      browse_about_icon_button,
							      browse_home_icon_button);
	}

	/** Destructor. */
	public void destroy() {
	}

	/** Called to refresh the components. */
	public void gainFocus() {
             // Retrieve all of the elements that are dependant on default language.
	    collection_extra_collectionmeta = CollectionDesignManager.collectionmeta_manager.getMetadatum(StaticStrings.COLLECTIONMETADATA_COLLECTIONEXTRA_STR);
	    collection_name_collectionmeta = CollectionDesignManager.collectionmeta_manager.getMetadatum(StaticStrings.COLLECTIONMETADATA_COLLECTIONNAME_STR);
	    
	    creator_collectionmeta = new CollectionMeta(CollectionDesignManager.collect_config.getCreator());
	    icon_collection_collectionmeta = CollectionDesignManager.collectionmeta_manager.getMetadatum(StaticStrings.COLLECTIONMETADATA_ICONCOLLECTION_STR);
	    icon_collection_small_collectionmeta = CollectionDesignManager.collectionmeta_manager.getMetadatum(StaticStrings.COLLECTIONMETADATA_ICONCOLLECTIONSMALL_STR);
	    maintainer_collectionmeta = new CollectionMeta(CollectionDesignManager.collect_config.getMaintainer());
	    // Make sure the components are up to date
	    creator_emailfield.setText(creator_collectionmeta.getValue(CollectionMeta.TEXT));
	    creator_emailfield.setCaretPosition(0);
	    description_textarea.setText(collection_extra_collectionmeta.getValue(CollectionMeta.TEXT));
	    description_textarea.setCaretPosition(0);
	    icon_textfield.setText(icon_collection_collectionmeta.getValue(CollectionMeta.TEXT));
	    icon_textfield.setCaretPosition(0);
	    maintainer_emailfield.setText(maintainer_collectionmeta.getValue(CollectionMeta.TEXT));
	    maintainer_emailfield.setCaretPosition(0);
	    name_textfield.setText(collection_name_collectionmeta.getValue(CollectionMeta.TEXT));
	    name_textfield.setCaretPosition(0);
	    small_icon_textfield.setText(icon_collection_small_collectionmeta.getValue(CollectionMeta.TEXT));
	    small_icon_textfield.setCaretPosition(0);
	    public_checkbox.setSelected(public_collectionmeta.getValue(CollectionMeta.TEXT).equals(StaticStrings.TRUE_STR));
            ready = true;
	}

	/** Called to store the current value of the components. */
	public void loseFocus() {
	    // String values. Have to test if this component has actually ever recieved focus anyway.
	    
            if (!ready) return;

	    boolean preserveTags = true; // for coll description, allow HTML tags to be saved as HTML tags
	    public_collectionmeta.setValue((public_checkbox.isSelected() ? StaticStrings.TRUE_STR : StaticStrings.FALSE_STR));
	    String creator_email_str = creator_emailfield.getText();
	    creator_collectionmeta.setValue(creator_email_str);
	    collection_extra_collectionmeta.setValue(description_textarea.getText(), preserveTags);
	    icon_collection_collectionmeta.setValue(icon_textfield.getText());
	    maintainer_collectionmeta.setValue(maintainer_emailfield.getText());
	    icon_collection_small_collectionmeta.setValue(small_icon_textfield.getText());
	    collection_name_collectionmeta.setValue(name_textfield.getText());
	    
    }

	/** Listens for a click on either browse button, and when detected opens a file browser window initially pointed at the images folder of the collection. Once a user has selected a path, does it's best to construct the best address to the resource, such as _httpcollection_/images/about.gif */
	private class BrowseListener
	    implements ActionListener {

	    private String prefix;

	    public BrowseListener(String prefix_raw) {
		this.prefix = prefix_raw.replaceAll(StaticStrings.COLNAME_PATTERN, CollectionManager.getLoadedCollectionName());
	    }

	    public void actionPerformed(ActionEvent event) {
		// Open an almost standard file browser to the images folder of the current collection
		File images_folder = new File(CollectionManager.getLoadedCollectionImagesDirectoryPath());
		// If images isn't already there, create it
		if(!images_folder.exists()) {
		    images_folder.mkdirs();
		}
		JFileChooser file_chooser = new JFileChooser(images_folder);
		file_chooser.setAcceptAllFileFilterUsed(false);
		file_chooser.setDialogTitle(Dictionary.get("CDM.General.Browser_Title"));
		file_chooser.setFileFilter(new ImageFilter());
		file_chooser.setSize(400,300);
		GUIUtils.disableRename(file_chooser);
		int value = file_chooser.showOpenDialog(Gatherer.g_man);
		// If the user hasn't cancelled, retrieve the file path selected
		if(value == JFileChooser.APPROVE_OPTION) {
		    // If the file isn't in the images folder, then ask the user if they want to copy it there
		    File file = file_chooser.getSelectedFile();
		    if (!file.getParentFile().equals(images_folder)) {
			// Copy the file
			try {
			    File collection_image_file = new File(images_folder, file.getName());
			    Gatherer.f_man.getQueue().copyFile(file, collection_image_file, true);

			    // If we're using a remote Greenstone server, upload the image
			    if (Gatherer.isGsdlRemote) {
				Gatherer.remoteGreenstoneServer.uploadCollectionFile(
                                   CollectionManager.getLoadedCollectionName(), collection_image_file);
			    }
			}
			catch(Exception exception) {
			    DebugStream.printStackTrace(exception);
			    // Show warning
			    String[] args = new String[] {file.getAbsolutePath(), images_folder.getAbsolutePath()};
			    JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("CDM.General.Image_Copy_Failed", args), Dictionary.get("General.Error"), JOptionPane.ERROR_MESSAGE);
			    // Nothing else we can do.
			    return;
			}
		    }

		    // Create the path starting _httpcollection_/images/<filename>
		    String path = prefix + file.getName();
		    if (Gatherer.GS3){
			path = file.getName();
		    }
		    if(event.getSource() == browse_about_icon_button) {
			icon_textfield.setText(path);
                        icon_collection_collectionmeta.setValue(icon_textfield.getText());
		    }
		    else {
			small_icon_textfield.setText(path);
                        icon_collection_small_collectionmeta.setValue(small_icon_textfield.getText());
		    }
		    path = null;
		}
	    }

	    /** ImageFilter.java is a 1.4 example used by FileChooserDemo2.java. */
	    private class ImageFilter
		extends javax.swing.filechooser.FileFilter {

		private Pattern pattern = null;

		public ImageFilter() {
		    pattern = Pattern.compile(".*\\.(gif|png|jpe?g)");
		}

		// Accept all directories and all .col files
		public boolean accept(File f) {
		    String filename = f.getName().toLowerCase();
		    Matcher matcher = pattern.matcher(filename);
		    return f.isDirectory() || matcher.matches();
		}

		// The description of this filter
		public String getDescription() {
		    return Dictionary.get("CDM.General.Image_Filter");
		}
	    }
	}

	private class CollectionTitleUpdater
	    implements DocumentListener {
	    /** Gives notification that an attribute or set of attributes changed. */
	    public void changedUpdate(DocumentEvent e) {
		setTitle();
	    }
	    /** Gives notification that there was an insert into the document. */
	    public void insertUpdate(DocumentEvent e) {
		setTitle();
	    }
	    /** Gives notification that a portion of the document has been removed. */
	    public void removeUpdate(DocumentEvent e) {
		setTitle();
	    }
	    
	    private void setTitle() {
		// Set the title
		String collection_title = name_textfield.getText();
		String collection_name = CollectionManager.getLoadedCollectionName(true);
		Gatherer.g_man.setTitle(collection_title, collection_name);
                collection_name_collectionmeta.setValue(collection_title);
		collection_title = null;
		collection_name = null;
	    }
	}
    }
}
