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

import dev.dinauer.maven.maven.shared.Extensions;
import dev.dinauer.maven.maven.shared.Parser;
import dev.dinauer.maven.maven.shared.ParserResult;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.Strings;

import java.util.List;
import java.util.Optional;

public class ExtensionParser implements Parser<Extensions>
{
    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 ParserResult<Extensions> 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 ParserResult<>(firstLevelBase, new Extensions(FileExt.valueOf(firstLevelExtension.toUpperCase()), Optional.empty()));
        }
        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 ParserResult<>(secondLevelBase, new Extensions(FileExt.valueOf(secondLevelExtension.toUpperCase()), Optional.of(FileHash.valueOf(firstLevelExtension.toUpperCase()))));
            }
        }
        throw new RuntimeException();
    }
}
