package com.atlassian.bitbucket.installer.validation;

import com.google.common.collect.ImmutableList;

import java.io.File;
import java.util.List;
import java.util.Optional;

/**
 * NOTE: The version of a HomeDirectoryStructure is not equal to the version of Bitbucket.
 * It is just a convenient way to mark if a directory is a valid home directory or not.
 *
 * NOTE#2: In case it is confusing, this class as well as {@link HomeDirectoryValidationStrategy}
 * is not yet been used anywhere by the installer. This could be used in the future to refine the installation further.
 * As it can detect the "version" of the home directory
 */
public enum HomeDirectoryStructure {
    // post shared structure
    V2_0("caches", "export", "log", "plugins", "shared", "shared/data", "shared/config", "shared/plugins", "tmp"),

    // pre shared structure (pre-Stash 3.2)
    V1_0("caches", "export", "log", "plugins", "data", "config", "tmp");

    private final List<String> contents;

    HomeDirectoryStructure(String... contents) {
        this.contents = ImmutableList.copyOf(contents);
    }

    public List<String> getContents() {
        return contents;
    }

    public static Optional<HomeDirectoryStructure> match(File homeDirectory) {
        for (HomeDirectoryStructure version : values()) {
            if (matchContents(homeDirectory, version.contents)) {
                return Optional.of(version);
            }
        }

        return Optional.empty();
    }

    private static boolean matchContents(File homeDirectory, List<String> expectedDirectories) {
        for (String path : expectedDirectories) {
            File file = new File(homeDirectory, path);
            if (!file.isDirectory()) {
                return false;
            }
        }
        return true;
    }
}
