package com.atlassian.bitbucket.installer;

import com.atlassian.bitbucket.Product;
import com.install4j.api.Util;

import java.io.File;
import java.io.Serializable;

public class DefaultDirectoryResolver implements Serializable {

    private static final String PATH_FORMAT = "%s" + File.separator + "%s" + File.separator + "%s";

    private final Platform platform;
    private final String version;

    public DefaultDirectoryResolver(Platform platform, String version) {
        this.platform = platform;
        this.version = version;
    }

    public File resolveInstallationDirectory(boolean isAdmin) {
        return buildInstallationDirectory(isAdmin).getAbsoluteFile();
    }

    public File resolveHomeDirectory(boolean isAdmin) {
        return resolveHomeDirectory(isAdmin, Product.NAME);
    }

    public File resolveHomeDirectory(boolean isAdmin, String productName) {
        String name = Platform.LINUX.equals(platform) ? productName.toLowerCase() : productName;
        String homeDirectory = String.format(PATH_FORMAT, platform.getAtlassianPrefix(), platform.getApplicationData(), name);
        File homeDirectoryFile = isAdmin ? new File(platform.getAdminHomePrefix(), homeDirectory) : new File(Util.getUserHome(), homeDirectory);
        return homeDirectoryFile.getAbsoluteFile();
    }

    private File buildInstallationDirectory(boolean isAdmin) {
        String productName = File.separator + (Platform.LINUX.equals(platform) ? Product.NAME.toLowerCase() : Product.NAME);
        String installDirectory = String.format(PATH_FORMAT, platform.getAtlassianPrefix(), productName, File.separator + version);
        return isAdmin ? new File(platform.getAdminInstallPrefix(), installDirectory) : new File(Util.getUserHome(), installDirectory);
    }
}
