package backupAndRecovery;

import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Vector;
import main.ConfigurationReader;
import network.RepositoryPoller;

/**
 * Simple implementation of Round Robin rotation scheme.
 * 
 * @author Marcel Duris
 */
public class RoundRobin implements IRotationScheme {

    /**
     * This method implements Round Robin aproach to backup media rotation.
     * Existing backups are sorted by time of their creation. Oldest backups are
     * deleted, only number of the newest backups configured are left.
     *
     * Backups are choosen by their filename, i.e files of same filename are
     * considered related. No other parameters, like name of user, who created
     * backup are considered.
     *
     * @param meta information about any backup in set of backups to be rotated
     */
    public void rotate(BackupMetaContainer meta) {
        RepositoryPoller poller = new RepositoryPoller();
        BackupMetaContainer[] existing =
                poller.pollForFilename(meta.getFilename());
        //uff, not really good design of rest of application if I have to do it this way
        //i.e to find backups of single SIMILAR filename and then filter
        //EXACT filenames
        Vector<BackupMetaContainer> matching = new Vector<BackupMetaContainer>();
        for (BackupMetaContainer ex : existing) {
            if (ex.getFilename().equals(meta.getFilename())) {
                matching.add(ex);
            }
        }

        Collections.sort(matching, new Comparator<BackupMetaContainer>() {

            public int compare(BackupMetaContainer o1, BackupMetaContainer o2) {
                Date d1 = o1.getBackupTime();
                Date d2 = o2.getBackupTime();

                return d1.compareTo(d2);
            }
            //Implement equals?
        });

        int oldest = ConfigurationReader.getCfg().getMaxBackupCount();
        for (int i = oldest; i < matching.size(); i++) {
            // nothing advanced, round robin, delete oldest
            Delete.delete(matching.get(i), true);
        }
    }
}
