package be.iminds.ilabt.jfed.util;

import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

/**
 * OSDetector
 */
public class OSDetector {
    private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(OSDetector.class);

    public enum OS { WIN, UNIX, MAC }

    public static OS findOS() {
        final String osname = System.getProperty("os.name").toLowerCase();
        if (osname.contains("win")) {
            return OSDetector.OS.WIN;
        }

        if (osname.contains("mac")) {
            return OSDetector.OS.MAC;
        }

        if (osname.contains("nix") || osname.contains("nux") || osname.contains("aix") || osname.contains("bsd")) {
            return OSDetector.OS.UNIX;
        }

        LOG.warn("OSDetector could not detect os from os.name=\""+osname+"\"");

        return null;
    }

    public static final OS os = findOS();




    // filters for OSes

    public interface OSFilter {
        boolean includedOs(OS os);
    }

    public static class OneOsFilter implements OSFilter {
        private final OS os;
        private final boolean invert;
        public OneOsFilter(OS os) { this.os = os; this.invert = false; }
        public OneOsFilter(OS os, boolean invert) { this.os = os; this.invert = invert; }
        public boolean includedOs(OS o) {
            if (invert)
                return !Objects.equals(os, o);
            else
                return Objects.equals(os, o);
        }
    }
    public static class MultiOsFilter implements OSFilter {
        private final Collection<OS> os;
        private final boolean invert;
        public MultiOsFilter(Collection<OS> o) { this.os = o; this.invert = false; }
        public MultiOsFilter(Collection<OS> o, boolean invert) { this.os = o; this.invert = invert; }
        public boolean includedOs(OS o) {
            if (invert)
                return !os.contains(o);
            else
                return os.contains(o);
        }
    }
    public static OSFilter getUnixLikeOsFilter() {
        List<OS> oses = new ArrayList<>();
        oses.add(OS.UNIX);
        oses.add(OS.MAC);
        return new MultiOsFilter(oses);
    }
}
