package dev.dinauer.maven.maven.core;

import dev.dinauer.maven.jpa.maven.Jar;
import dev.dinauer.maven.jpa.maven.Version;
import dev.dinauer.maven.maven.core.model.MavenContext;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.BadRequestException;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import org.apache.commons.codec.digest.DigestUtils;

import java.util.List;

@ApplicationScoped
public class JarService
{
    @Inject
    VersionService versionService;

    public Response store(MavenContext mavenContext, byte[] body)
    {
        String md5 = DigestUtils.md5Hex(body);
        String sha1 = DigestUtils.sha1Hex(body);
        Version version = versionService.findOrCreate(mavenContext.groupId(), mavenContext.artifactId(), mavenContext.version().getRaw());
        if (!existsJar(version.getJars(), mavenContext.file().getBase()))
        {
            version.getJars().add(new Jar().setJar(body).setMd5(md5).setSha1(sha1).setVersion(version).setUrl(mavenContext.path()).setFilename(mavenContext.file().getFilename()));
            versionService.persist(version);
            return Response.status(Response.Status.CREATED).build();
        }
        return Response.status(Response.Status.CONFLICT).build();
    }

    public Response find(MavenContext context)
    {
        return Response.status(Response.Status.OK).type(MediaType.APPLICATION_OCTET_STREAM).entity(findJar(context).getJar()).build();
    }

    public Response findHash(MavenContext context)
    {
        switch (context.file().getHash())
        {
            case SHA1 ->
            {
                return Response.status(Response.Status.OK).type(MediaType.TEXT_PLAIN).entity(findJar(context).getSha1()).build();
            }
            case MD5 ->
            {
                return Response.status(Response.Status.OK).type(MediaType.TEXT_PLAIN).entity(findJar(context).getMd5()).build();
            }
        }
        throw new BadRequestException();
    }

    private Jar findJar(MavenContext context)
    {
        return versionService.findOptional(context.groupId(), context.artifactId(), context.version().getRaw()).orElseThrow().getJarByFilename(context.file().getFilename()).orElseThrow();
    }

    private boolean existsJar(List<Jar> jars, String fileBase)
    {
        for (Jar jar : jars)
        {
            if (fileBase.equals(jar.getFilename()))
            {
                return true;
            }
        }
        return false;
    }
}
