package de.renew.navigator.vc.impl;

import java.io.File;
import java.util.LinkedList;

import org.apache.log4j.Logger;

import de.renew.navigator.vc.Repository;
import de.renew.navigator.vc.VersionControl;
import de.renew.navigator.vc.VersionControlAggregator;


/**
 * @author Konstantin Simon Maria Moellers
 * @version 2015-10-13
 */
public class VersionControlAggregatorImpl implements VersionControlAggregator {

    /**
     * Log4j logger instance.
     */
    public static final Logger LOGGER = Logger.getLogger(VersionControlAggregatorImpl.class);
    private final LinkedList<VersionControl> _versionControls = new LinkedList<>();

    @Override
    public void addVersionControl(VersionControl vcs) {
        _versionControls.add(vcs);
    }

    @Override
    public boolean removeVersionControl(VersionControl vcs) {
        return _versionControls.remove(vcs);
    }

    @Override
    public boolean controls(File workingDir) {
        for (VersionControl versionControl : _versionControls) {
            if (versionControl.controls(workingDir)) {
                return true;
            }
        }

        return false;
    }

    @Override
    public boolean diff(File file) {
        final Repository r = findRepository(file);
        if (r == null) {
            warnNotInARepository(file);
            return false;
        }

        return r.getVersionControl().diff(file);
    }

    @Override
    public boolean log(File file) {
        final Repository r = findRepository(file);
        if (r == null) {
            warnNotInARepository(file);
            return false;
        }

        return r.getVersionControl().log(file);
    }

    @Override
    public String getName() {
        StringBuilder builder = new StringBuilder("[");
        boolean isFirst = true;
        for (VersionControl versionControl : _versionControls) {
            if (!isFirst) {
                builder.append(',');
            } else {
                isFirst = false;
            }
            builder.append(versionControl.getName());
        }
        builder.append(']');

        return builder.toString();
    }

    @Override
    public Repository findRepository(File fileInRepository) {
        for (VersionControl accessor : _versionControls) {
            if (accessor.controls(fileInRepository)) {
                return accessor.findRepository(fileInRepository);
            }
        }

        warnNotInARepository(fileInRepository);
        return null;
    }

    private void warnNotInARepository(File file) {
        LOGGER.warn(
            "The file " + file.getAbsolutePath() + " seems not to be in a repository known to "
                + getName());
    }
}