/**
 *#########################################################################
 *
 * 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: Greenstone Project, NZDL, University of Waikato
 *
 * Copyright (C) 2023 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.gui;

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import org.greenstone.gatherer.Configuration;
import org.greenstone.gatherer.Dictionary;
import org.greenstone.gatherer.Gatherer;
import org.greenstone.gatherer.collection.CollectionManager;
import org.greenstone.gatherer.util.JarTools;
import org.greenstone.gatherer.util.Utility;

/** A dialog that warns about the presence of the archives_keepold folder when starting
 * off a build and asks what to do about it.
 * When the build button is pressed, GLI should check for the existence of 'archives_keepold',
 * and if it exists at that point, it should
 * open up a pop-up that asks the user:
 * - if they want to revert 'archives' back to the previous version (keepold) before building (the default),
 * - proceed with the build (previous restore-point will be lost),
 * - or else cancel the build.
*/
public class WarnIncrBuildDialog
    extends ModalDialog 
    implements ActionListener, KeyListener
{
    public static final int CANCEL = 0;
    public static final int USE_KEEPOLD = 1;
    public static final int REMOVE_KEEPOLD = 2;

    private static final Dimension SIZE = new Dimension(650, 200);    

    
    private int result = REMOVE_KEEPOLD; // default

    private JButton revert_button;
    private JButton remove_button;
    private JButton cancel_button;


    public WarnIncrBuildDialog()
    {
	super(Gatherer.g_man, "Warning", true);
        this.setComponentOrientation(Dictionary.getOrientation());

	// Now build dialog.
	setSize(SIZE);	
	setTitle(Dictionary.get("WarnIncrBuildDialog.Title"));
	
	// Creation
	JPanel content_pane = (JPanel) getContentPane();
        content_pane.setComponentOrientation(Dictionary.getOrientation());
	JPanel text_pane = new JPanel();
        text_pane.setComponentOrientation(Dictionary.getOrientation());
        
	String gmedium_image = "gatherer_medium.png";
	if (Configuration.fedora_info != null && Configuration.fedora_info.isActive()) {
	    gmedium_image = "fli-" + gmedium_image;
	}

	JLabel icon_label = new JLabel(JarTools.getImage(gmedium_image));
        icon_label.setComponentOrientation(Dictionary.getOrientation());

	JTextArea text_area = new JTextArea();
        text_area.setComponentOrientation(Dictionary.getOrientation());
	text_area.setEditable(false);
	text_area.setLineWrap(true);
	text_area.setText(Dictionary.get("WarnIncrBuildDialog.Message"));
	text_area.setCaretPosition(0);
	text_area.setWrapStyleWord(true);

	JPanel bottom_pane = new JPanel();
        bottom_pane.setComponentOrientation(Dictionary.getOrientation());
	
	JPanel control_pane = new JPanel();
        control_pane.setComponentOrientation(Dictionary.getOrientation());
	revert_button = new GLIButton(Dictionary.get("WarnIncrBuildDialog.Revert"), Dictionary.get("WarnIncrBuildDialog.Revert_Tooltip"));
	remove_button = new GLIButton(Dictionary.get("WarnIncrBuildDialog.Remove"), Dictionary.get("WarnIncrBuildDialog.Remove_Tooltip"));
	cancel_button = new GLIButton(Dictionary.get("General.Cancel"), Dictionary.get("General.Pure_Cancel_Tooltip"));
	
	// Connection
	revert_button.addActionListener(this);
	remove_button.addActionListener(this);	
	cancel_button.addActionListener(this);
	revert_button.addKeyListener(this);
	remove_button.addKeyListener(this);
	cancel_button.addKeyListener(this);
	getRootPane().setDefaultButton(revert_button);

	// Layout
	icon_label.setBorder(BorderFactory.createEmptyBorder(0,0,0,5));

	text_pane.setLayout(new BorderLayout());
	text_pane.add(icon_label, BorderLayout.LINE_START);
	text_pane.add(new JScrollPane(text_area), BorderLayout.CENTER);

	control_pane.setLayout(new GridLayout(1,3,5,0)); // 1,3,5,0?
	control_pane.add(revert_button);
	control_pane.add(remove_button);
	control_pane.add(cancel_button);	
	
	bottom_pane.setBorder(BorderFactory.createEmptyBorder(5,0,0,0));
	bottom_pane.setLayout(new BorderLayout());
	bottom_pane.add(control_pane, BorderLayout.LINE_END);

	content_pane.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
	content_pane.setLayout(new BorderLayout());
	content_pane.add(text_pane, BorderLayout.CENTER);
	content_pane.add(bottom_pane, BorderLayout.SOUTH);

	// Position
	Dimension size = getSize();
	if (Gatherer.g_man != null) {
	    Rectangle frame_bounds = Gatherer.g_man.getBounds();
	    setLocation(frame_bounds.x + (frame_bounds.width - size.width) / 2, frame_bounds.y + (frame_bounds.height - size.height) / 2);
	}
	else {
	    Dimension screen_size = Toolkit.getDefaultToolkit().getScreenSize();
	    setLocation((screen_size.width - size.width) / 2, (screen_size.height - size.height) / 2);
	}
    }

    public void actionPerformed(ActionEvent event) {
	boolean valid_value = true;
	if(event.getSource() == cancel_button) {
	    result = CANCEL;
	}
	else {
	    String archives_keepold = CollectionManager.getLoadedCollectionArchivesKeepOldDirectoryPath();
	    File archives_keepold_dir = new File(archives_keepold);
	    if(event.getSource() == revert_button) {
		result = USE_KEEPOLD;

		String archives = CollectionManager.getLoadedCollectionArchivesDirectoryPath();
		File archives_dir = new File(archives);
		
		// we wouldn't even be here if archives_keepold_dir didn't exist, so no need to check
		// Delete archives_dir and move archives_keepold to archives
		if(archives_dir.exists() && !Utility.delete(archives_dir)) {
		    WarningDialog dialog = new WarningDialog(
			     "warning.UnableToDeleteFolder",
			     Dictionary.get("UnableToDeleteFolder.Title"),
			     Dictionary.get("UnableToDeleteFolder.Message",
					    archives_dir.getPath()),
			     null, false, false); 
		    
		    dialog.display();
		    dialog.dispose();
		    dialog = null;
		}
		// If no archives folder (any more), ready to move "archives_keepold" to "archives"
		if(!archives_dir.exists()) {
		    if(!archives_keepold_dir.renameTo(archives_dir)) {
			WarningDialog dialog = new WarningDialog("warning.UnableToRenameFolder",
				 Dictionary.get("UnableToRenameFolder.Title"),
				 Dictionary.get("UnableToRenameFolder.Message",
						new String[] {
						    archives_keepold_dir.getPath(),
						    archives_dir.getPath()}),
				 null, false, false); 
		    
			dialog.display();
			dialog.dispose();
			dialog = null;
		    }
		}
		
	    } else if(event.getSource() == remove_button) {
		result = REMOVE_KEEPOLD;
		
		if(!Utility.delete(archives_keepold_dir)) {
		    WarningDialog dialog = new WarningDialog(
			     "warning.UnableToDeleteFolder",
			     Dictionary.get("UnableToDeleteFolder.Title"),
			     Dictionary.get("UnableToDeleteFolder.Message",
					    archives_keepold_dir.getPath()),
			     null, false, false); 
		    
		    dialog.display();
		    dialog.dispose();
		    dialog = null;
		}

	    } 
	}
	// Done.
	setVisible(false);
    }

    /** Gives notification of key events on the buttons */
    public void keyPressed(KeyEvent e) {
	if (e.getKeyCode() == KeyEvent.VK_ENTER) {
	    // Enter: Click the button in focus
	    Object source = e.getSource();
	    if (source instanceof AbstractButton) {
		((AbstractButton) source).doClick();
	    }
	}
    }

    public void keyReleased(KeyEvent e) {}

    public void keyTyped(KeyEvent e) {}


    public int display() {
	setVisible(true);

	// Ask the parent to repaint, just to be sure
	if(Gatherer.g_man != null) {
	    Gatherer.g_man.repaint();
	}
	return result;
    }

    protected void processWindowEvent(WindowEvent event) {
	if(event.getID() == WindowEvent.WINDOW_ACTIVATED) {
	   revert_button.requestFocus();
	}
	else {
	    super.processWindowEvent(event);
	}
    }

}
