package io;

import java.util.Iterator;

/**
 * This class defines and iterates over names of parts of backup.
 *
 * @author Marcel Duris
 */
public class Partlist implements Iterable<String> {

    private String prefix;
    private boolean includeFragments = true;
    int n;
    int m;

    /**
     * Inner iterator.
     */
    public class PrefixlistIterator implements Iterator<String> {

        private int pos;
        private int n;
        private int m;

        public PrefixlistIterator(int n, int m) {
            pos = 0;
            this.n = n;
            this.m = m;
        }

        public PrefixlistIterator(int n, int m, boolean includeFragments) {
            if (includeFragments) {
                pos = 0;
            } else {
                pos = n;
            }
            this.n = n;
            this.m = m;
        }

        public boolean hasNext() {
            return pos < (m + n);
        }

        public String next() {
            String no = "00000" + pos;
            String dc = pos < n ? "d" : "c";

            pos++;

            no = no.substring(no.length() - 5);
            String filename = prefix + dc + no;

            return filename;
        }

        public void remove() {
            throw new UnsupportedOperationException("Not supported yet.");
        }
    }

    public Partlist(String prefix, int n, int m, boolean includeFragments) {
        this(prefix, n, m);
        this.includeFragments = includeFragments;
    }

    public Partlist(String prefix, int n, int m) {
        //check input
        if (n == 0) {
            this.n = Integer.MAX_VALUE;
        } else if (n < 0) {
            throw new IllegalArgumentException("Illegal part count.");
        } else {
            this.n = n;
        }

        if (n == 0) {
            this.m = Integer.MAX_VALUE;
        } else if (m < 0) {
            throw new IllegalArgumentException("Illegal part count.");
        } else {
            this.m = m;
        }

        this.prefix = prefix;
    }

    public Iterator<String> iterator() {
        return new PrefixlistIterator(n, m, includeFragments);
    }

    /**
     * Returns number of data fragments coresponding backup uses.
     *
     * @return number of data fragments
     */
    public int getDataCount() {
        return n;
    }

    /**
     * Returns number of checksum files calculated for this backup.
     *
     * @return number of checksums
     */
    public int getChecksumCount() {
        return m;
    }

    /**
     * Returns prefix of all backup files or name of backup.
     *
     * @return name of backup
     */
    public String getBackupName() {
        return prefix;
    }
}
