/*
 * File:     BackupCA.java
 * Project:  MPI Linguistic Application
 * Date:     03 April 2006
 *
 * Copyright (C) 2001-2006  Max Planck Institute for Psycholinguistics
 *
 * 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package mpi.eudico.client.annotator.commands;

import mpi.eudico.client.annotator.ElanLocale;
import mpi.eudico.client.annotator.Preferences;
import mpi.eudico.client.annotator.ViewerManager2;

import mpi.eudico.server.corpora.clom.TranscriptionStore;

import mpi.eudico.server.corpora.clomimpl.abstr.TranscriptionImpl;
import mpi.eudico.server.corpora.clomimpl.dobes.ACM23TranscriptionStore;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import java.util.Vector;
import java.util.logging.Logger;

import javax.swing.JOptionPane;
import javax.swing.Timer;


/**
 * This CommandAction is not intended to be used in a user interface  as an
 * Action for a button or menu item.<br>
 * This Action is only created after the user has chosen to use automatic
 * backup. Other ActionCommands set / change fields in this action whereupon
 * this action  changes or creates a backup Timer task.
 *
 * @author Han Sloetjes
 */
public class BackupCA extends CommandAction {
    /** Holds value of property DOCUMENT ME! */
    private static final Logger LOG = Logger.getLogger(BackupCA.class.getName());

    /** The delay for the backup thread */
    private int delay = 0;

    /** Only prompt the user once to save the file before backup starts */
    private boolean promptedOnce = false;

    /** The path of the .eaf file */
    private String filePath = "";

    /** The timer that manages backup process */
    private Timer timer;

    /** Holds value of property DOCUMENT ME! */
    protected ACM23TranscriptionStore transcriptionStore;

    /**
     * Creates a new BackupCA instance
     *
     * @param viewerManager the viewermanager
     */
    public BackupCA(ViewerManager2 viewerManager) {
        super(viewerManager, ELANCommandFactory.BACKUP);

        transcriptionStore = new ACM23TranscriptionStore();

        if (vm.getTranscription() instanceof TranscriptionImpl) {
            filePath = ((TranscriptionImpl) vm.getTranscription()).getPathName();
        }
    }

    /**
     * This CommandAction creates no Command. All the actions are performed by
     * this  CommandAction.
     */
    protected void newCommand() {
        command = null;
    }

    /**
     * There's no natural receiver for this CommandAction.
     *
     * @return <code>null</code>
     */
    protected Object getReceiver() {
        return null;
    }

    /**
     * Returns null.
     *
     * @return <code>null</code>
     */
    protected Object[] getArguments() {
        return null;
    }

    /**
     * Returns the delay of the current backup thread.
     *
     * @return the current delay of the timer task
     */
    public int getDelay() {
        return delay;
    }

    /**
     * Returns the path to the .eaf file.
     *
     * @return the path to the .eaf file
     */
    public String getFilePath() {
        return filePath;
    }

    /**
     * Changes the backup delay time and starts a new backup thread.
     *
     * @param delayTime the new delay of the timer task
     */
    public void setDelay(int delayTime) {
        if (delay != delayTime) {
            delay = delayTime;
            Preferences.set("BackUpDelay", delay, null);

            if (delayTime == 0) {
                if (timer != null) {
                    timer.stop();
                }
            } else {
                if (timer != null) {
                    timer.stop();

                    /*
                       timer.setDelay(delayTime);
                       } else {
                           createTimer();
                     */
                }

                createTimer();
            }
        }
    }

    /**
     * Sets the path of the backup file and creates a new backup thread.
     *
     * @param path the new path to the .eaf file
     */
    public void setFilePath(String path) {
        if (!path.equals(filePath)) {
            filePath = path;

            if (timer != null) {
                timer.stop();

                if (delay != 0) {
                    createTimer();
                }
            }
        }
    }

    /**
     * Stops the backup thread.
     */
    public void stopBackUp() {
        if (timer != null) {
            timer.stop();
        }
    }

    private void createTimer() {
        timer = new Timer(delay, new BackupActionListener());
        timer.start();
    }

    /**
     * The <code>ActionListener</code> for the backup Timer task. <br>
     * Performs the save  action every time it is notified by the Timer.
     *
     * @author Han Sloetjes
     * @version 1.1 20 Apr 2004
     */
    class BackupActionListener implements ActionListener {
        /**
         * Invokes <code>storeTranscription</code> on the
         * <code>Transcription</code> object.
         *
         * @param e the action event
         */
        public void actionPerformed(ActionEvent e) {
            if (!(vm.getTranscription() instanceof TranscriptionImpl)) {
                return;
            }

            if (transcriptionStore != null) {
                Vector visibleTiers = vm.getMultiTierControlPanel()
                                        .getVisibleTiers();

                try {
                    String path = null;

                    if (getFilePath().length() == 0) {
                        path = ((TranscriptionImpl) vm.getTranscription()).getPathName() +
                            ".001";
                    } else if (getFilePath().equals(TranscriptionImpl.UNDEFINED_FILE_NAME)) {
                        if (!promptedOnce) {
                            // prompt the user to save the file, but only once
                            JOptionPane.showMessageDialog(ELANCommandFactory.getRootFrame(
                                    vm.getTranscription()),
                                ElanLocale.getString("Message.Backup"),
                                ElanLocale.getString("Message.Warning"),
                                JOptionPane.WARNING_MESSAGE);
                            promptedOnce = true;
                        }

                        // let the save action continue anyway 
                        path = getFilePath() + ".eaf.001";
                    } else {
                        path = getFilePath() + ".001";
                    }

                    transcriptionStore.storeTranscriptionIn(vm.getTranscription(),
                        null, visibleTiers, path, TranscriptionStore.EAF);
                } catch (SecurityException sex) {
                    LOG.severe(
                        "Cannot save a backup file - no write permission");
                }
            }
        }
    }
}
