package dev.dinauer.maven.maven.core.model;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.Strings;

import java.util.List;

public class ExtensionParser
{
    private static final List<String> FILE_TYPES = List.of("jar", "pom", "xml");
    private static final List<String> FILE_HASHES = List.of("md5", "sha1", "sha256", "sha512");

    public static Result parse(String raw)
    {
        String firstLevelExtension = FilenameUtils.getExtension(raw);
        String firstLevelBase = Strings.CI.removeEnd(raw, String.format(".%s", firstLevelExtension));
        if (FILE_TYPES.contains(firstLevelExtension))
        {
            return new Result(firstLevelBase, FileType.valueOf(firstLevelExtension.toUpperCase()), null);
        }
        if (FILE_HASHES.contains(firstLevelExtension))
        {
            String secondLevelExtension = FilenameUtils.getExtension(firstLevelBase);
            if (FILE_TYPES.contains(secondLevelExtension))
            {
                String secondLevelBase = Strings.CI.removeEnd(firstLevelBase, String.format(".%s", secondLevelExtension));
                return new Result(secondLevelBase, FileType.valueOf(secondLevelExtension.toUpperCase()), FileHash.valueOf(firstLevelExtension.toUpperCase()));
            }
        }
        throw new RuntimeException();
    }

    public record Result(String base, FileType ext, FileHash hashExt)
    {
    }
}
