/**
 *#########################################################################
 *
 * 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.
 *
 * <BR><BR>
 *
 * Author: Shaoqun Wu, Greenstone Digital Library, University of Waikato
 *
 * <BR><BR>
 *
 * Copyright (C) 2006 New Zealand Digital Library Project
 *
 * <BR><BR>
 *
 * 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.
 *
 * <BR><BR>
 *
 * 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.
 *
 * <BR><BR>
 *
 * 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.gems;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Collection;
import java.util.Vector;

import org.greenstone.gatherer.Configuration;
import org.greenstone.gatherer.Dictionary;
import org.greenstone.gatherer.gui.ModalDialog;
import org.greenstone.gatherer.gui.GLIButton;

public class NewMetadataSetPrompt 
    extends ModalDialog {

    static private Dimension SIZE = new Dimension(500, 320);
        
    private ArrayList available_metadata_sets;
    private ArrayList listeners; 

    private JButton ok_button = null;
    private JButton cancel_button = null;    
    private JComboBox base_metadata_combo;
    private NewMetadataSetPrompt self;
    private MetadataSetManager meta_manager;
    private JTextArea description_textarea = null;
    private JTextField title_field;
    private JTextField namespace_field;

    private boolean cancelled = false;
    
    public NewMetadataSetPrompt(Frame parent,MetadataSetManager msm) {
	super(parent, true);
        self = this;
	listeners = new ArrayList();
	meta_manager = msm;

	setSize(SIZE);
	setTitle(Dictionary.get("GEMS.NewMetadataSetPrompt.Title"));
	
	JPanel content_pane = (JPanel) getContentPane();
        content_pane.setOpaque(true);
	
	JLabel  instruction_label = new JLabel(Dictionary.get("GEMS.NewMetadataSetPrompt.Instructions"));
	instruction_label.setOpaque(true);
	
	JLabel  title_label = new JLabel(Dictionary.get("GEMS.NewMetadataSetPrompt.Metadata_Title"));
	title_label.setOpaque(true);
                 
        title_field = new JTextField();

	JPanel title_pane = new JPanel(new BorderLayout(5,5));
        title_pane.add(title_label,BorderLayout.WEST);
        title_pane.add(title_field, BorderLayout.CENTER);

	
	JLabel  namespace_label = new JLabel(Dictionary.get("GEMS.NewMetadataSetPrompt.Metadata_Namespace"));
 	namespace_label.setOpaque(true);
                 
        namespace_field = new JTextField();

	JPanel namespace_pane = new JPanel(new BorderLayout(5,5));
        namespace_pane.add(namespace_label,BorderLayout.WEST);
        namespace_pane.add(namespace_field, BorderLayout.CENTER);

        
        JPanel info_pane = new JPanel();
        info_pane.setLayout(new BorderLayout(5,5));
        info_pane.add(instruction_label,BorderLayout.NORTH);
	info_pane.add(title_pane,BorderLayout.CENTER);
        info_pane.add(namespace_pane,BorderLayout.SOUTH);
        

	JLabel description_label = new JLabel(Dictionary.get("GEMS.Set_Description"));
	description_label.setOpaque(true);

	description_textarea = new JTextArea();
        description_textarea.setLineWrap(true); 
        description_textarea.setWrapStyleWord(true);

	JPanel description_pane = new JPanel();
        description_pane.setLayout(new BorderLayout());
        description_pane.add(description_label,BorderLayout.NORTH);
	description_pane.add(new JScrollPane(description_textarea),BorderLayout.CENTER);

       
	JLabel  base_label = new JLabel(Dictionary.get("GEMS.NewMetadataSetPrompt.Base_MetadataSet"));
	base_label.setOpaque(true);
        
        base_metadata_combo = new JComboBox();
	base_metadata_combo.setRenderer(new MetadatSetListCellRenderer());
	
	JPanel base_pane = new JPanel(new BorderLayout(5,5));
        base_pane.add(base_label,BorderLayout.WEST);
        base_pane.add(base_metadata_combo, BorderLayout.CENTER);


	JPanel button_pane = new JPanel();
	ok_button = new GLIButton(Dictionary.get("General.OK"), Dictionary.get("General.OK_Tooltip"));       	
	cancel_button = new GLIButton(Dictionary.get("General.Cancel"), Dictionary.get("General.Cancel_Tooltip"));
      

	// Add listeners
	ok_button.addActionListener(new ActionListener() {
		public void actionPerformed(ActionEvent event) {
		    if (createNewSet()) {
			self.dispose();
		    } // else if that returned false, then we leave the
		    // prompt there for them to change their input
		}
	    });

				    
	cancel_button.addActionListener(new ActionListener() {
		public void actionPerformed(ActionEvent event) {
		    cancelled = true;
		    self.dispose();
		}
	    });
	
 
	button_pane.setLayout(new GridLayout(1,2));
	button_pane.add(ok_button);
	button_pane.add(cancel_button);
	
	JPanel bottom_pane = new JPanel(new GridLayout(2,1,5,5));
	bottom_pane.add(base_pane);
	bottom_pane.add(button_pane);
	
	content_pane.setLayout(new BorderLayout(5,5));
	content_pane.add(info_pane, BorderLayout.NORTH);
	content_pane.add(description_pane, BorderLayout.CENTER);
	content_pane.add(bottom_pane, BorderLayout.SOUTH);
	content_pane.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
	
	// Show
	Dimension screen_size = Configuration.screen_size;
	setLocation((screen_size.width - SIZE.width) / 2, (screen_size.height - SIZE.height) / 2);
	setVisible(false);
	
    }
    
    
    public void display(){
	cancelled = false;
	available_metadata_sets =  meta_manager.getAvailableMetadataSets();
	Vector data = new Vector((Collection)available_metadata_sets);
	data.add(0,Dictionary.get("GEMS.NewMetadataSetPrompt.New_Metadata"));
	DefaultComboBoxModel  model = new DefaultComboBoxModel(data);
	title_field.setText("");
	namespace_field.setText("");
	description_textarea.setText("");
	base_metadata_combo.setModel(model); 
	setVisible(true);          
    }

    public boolean isCancelled() {
	return cancelled;
    }
    
    public void addMetadataSetListener(MetadataSetListener msl){
	listeners.add(msl);
   
    }

    private boolean createNewSet() {

	String title = title_field.getText();
	String namespace = namespace_field.getText();
	String description = description_textarea.getText();

	if (title == null || title.trim().equals("")){
	    JOptionPane.showMessageDialog(self, Dictionary.get("GEMS.NewMetadataSetPrompt.Title_Error_Message"), Dictionary.get("GEMS.NewMetadataSetPrompt.Title_Error"), JOptionPane.ERROR_MESSAGE);

	    return false;
	}

	if (namespace == null || namespace.trim().equals("")){
	    JOptionPane.showMessageDialog(self, Dictionary.get("GEMS.NewMetadataSetPrompt.Namespace_Error_Message"), Dictionary.get("GEMS.NewMetadataSetPrompt.Namespace_Error"), JOptionPane.ERROR_MESSAGE);
	    return false;
	}

	//check namespace conflict
	if (meta_manager.isNamespaceAlreadyUsed(namespace)) {
	    int result = JOptionPane.showOptionDialog(null,Dictionary.get("GEMS.Namespace_Conflict_Message"), Dictionary.get("GEMS.Namespace_Conflict"),JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE,null,GEMSConstants.DIALOG_OPTIONS,GEMSConstants.DIALOG_OPTIONS[0] );
	     
	    if (result != JOptionPane.OK_OPTION) return false;
	}

	Object selectedValue = base_metadata_combo.getSelectedItem();
        
	if (selectedValue != null ){
	    MetadataSetInfo meta_info = null;
               
	    if ((selectedValue instanceof MetadataSetInfo)){	  
		meta_info = (MetadataSetInfo)selectedValue;
	    }
	    else{
		meta_info = new MetadataSetInfo();                	
	    }
                
	    meta_info.setNew(true);
	    // clear all the language dependent attributes
	    meta_info.setLanguageDependentAttributes(new ArrayList());
	    meta_info.setMetadataSetName(title); 
	    meta_info.setMetadataSetDescription(description);
	    meta_info.setNamespace(namespace);
	    meta_info.setCurrentLanguage(meta_manager.getCurrentLanguage());
	    notifyListeners(meta_info);
	}
	return true;
    }

 
    private void notifyListeners(MetadataSetInfo set_info){
	MetadataSetEvent mse = new MetadataSetEvent(set_info);
	for(int i=0;i<listeners.size();i++){
	    MetadataSetListener msl = (MetadataSetListener)listeners.get(i);
	    msl.metadataSetChanged(mse);          
	}	
    }

    private class MetadatSetListCellRenderer extends JLabel 
	implements ListCellRenderer {
	public  MetadatSetListCellRenderer() {
	    setOpaque(true);
	}
	
	public Component getListCellRendererComponent(JList list,
						      Object value,
						      int index,
						      boolean isSelected,
						      boolean cellHasFocus)
	{
	    String name= "unknown";

	    if (value instanceof MetadataSetInfo){
		MetadataSetInfo meta_info = (MetadataSetInfo) value;
		name = meta_info.getMetadataSetName(); //get the name of metadata set
		setText(name);
	    }
	    else {
		setText(value.toString());
	    }

	    if (isSelected) {
		setBackground(list.getSelectionBackground());
		setForeground(list.getSelectionForeground());
	    }
	    else {
		setBackground(list.getBackground());
		setForeground(list.getForeground());
	    }
	              
	    return this;
	}
    }
       
}
