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

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

import java.util.List;

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

    private String raw;
    private String base;
    private FileType type;
    private FileHash hash;

    public String getRaw()
    {
        return raw;
    }

    public File setRaw(String raw)
    {
        this.raw = raw;
        return this;
    }

    public String getBase()
    {
        return base;
    }

    public File setBase(String base)
    {
        this.base = base;
        return this;
    }

    public FileType getType()
    {
        return type;
    }

    public File setType(FileType type)
    {
        this.type = type;
        return this;
    }

    public FileHash getHash()
    {
        return hash;
    }

    public File setHash(FileHash hash)
    {
        this.hash = hash;
        return this;
    }

    public static File parse(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(FileType.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(FileType.valueOf(secondaryExtension.toUpperCase()));
                file.setBase(secondaryBase);
                return file;
            }
        }
        throw new BadRequestException();
    }
}
