package backupAndRecovery;

import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Vector;
import main.ConfigurationReader;
import network.RepositoryPoller;
import org.apache.log4j.Logger;
import schedule.ITask;
import schedule.ScheduleConfigManager;
import schedule.Scheduler;

/**
 * This class provides convenient way to delete existing backups. To
 * successfully delete distributed backup, single delete request is not
 * sufficient. Backup has to be deleted repeatedly to ensure all fragments
 * have been deleted.
 * 
 * @author Marcel Duris
 */
public class Delete {

    /**
     * Performs one time deletion of backup.
     *
     * @param meta metainformation about backup to be deleted
     */
    public static void delete(final BackupMetaContainer meta) {
        Logger.getLogger("qbackup").info("Deleting backup " +
                meta.getBackupName() + " of file " + meta.getFilename());
        new Thread() {

            @Override
            public void run() {
                RepositoryPoller poller = new RepositoryPoller();
                poller.delete(meta);
            }
        }.start();
    }

    /**
     * Enables user to repeatedly delete backup. In addition to one time
     * deletion of backup, if specified by parameter, attempts to delete
     * backup are repeated every hour for one week.
     *
     * Repeated deletion is required to ensure backup has been deleted from
     * computers not connected to network at time of one time deletion.
     * However, to succesfully delete fragment, these nodes and local node
     * have to be connected to network at the same time for at least one hour.
     *
     * @param meta metainformation about backup to be deleted
     * @param repeat true if additional attempts are to be made
     */
    public static void delete(BackupMetaContainer meta, boolean repeat) {
        if (repeat) {
            try {
                Date notAfter = new Date(new Date().getTime() + 7 * 24 * 60 * 60 * 1000);
                ScheduleConfigManager sManager =
                        ScheduleConfigManager.getScheduleConfigManager();
                sManager.addTask(ScheduleConfigManager.DELETE, meta.getXmlString(),
                        ITask.ANYTIME, ITask.ANYTIME, ITask.ANYTIME, Calendar.getInstance().get(Calendar.MINUTE),
                        notAfter);
                sManager.saveConfig();
                Scheduler scheduler = Scheduler.getScheduler();
                scheduler.clear();
                sManager.parseFile(scheduler);
                scheduler.reschedule();
            } catch (Exception e) {
                Logger.getLogger("qbackup").info("Scheduling repeated delete unsuccessful");
            }
        }

        delete(meta);
    }
}
