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

import jakarta.ws.rs.BadRequestException;
import org.apache.commons.io.FilenameUtils;

import java.util.List;

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

    public static File parse(String artifactId, String version, String raw)
    {
        File file = new File().setRaw(raw);
        String extension = FilenameUtils.getExtension(raw);
        String base = FilenameUtils.getBaseName(raw);
        if (FILE_TYPES.contains(extension.toLowerCase()))
        {
            file.setType(FileExt.valueOf(extension.toUpperCase()));
            file.setBase(base);
            file.setHash(FileHash.NONE);
            return file;
        }
        if (FILE_HASHES.contains(extension))
        {
            file.setHash(FileHash.valueOf(extension.toUpperCase()));
            String secondaryExtension = FilenameUtils.getExtension(base);
            String secondaryBase = FilenameUtils.getBaseName(base);
            if (FILE_TYPES.contains(secondaryExtension.toLowerCase()))
            {
                file.setType(FileExt.valueOf(secondaryExtension.toUpperCase()));
                file.setBase(secondaryBase);
                return file;
            }
        }
        throw new BadRequestException();
    }
}
