package dev.dinauer.maven.maven.core.release;

import dev.dinauer.maven.maven.core.context.ReleaseContext;
import dev.dinauer.maven.maven.core.context.SnapshotContext;
import dev.dinauer.maven.maven.core.context.VersionContext;
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.WebApplicationException;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.NotImplementedException;

import java.util.List;

@ApplicationScoped
public class ReleaseJarService
{

    @Inject
    ReleaseJarRepo releaseJarRepo;

    @Inject
    ReleaseVersionService releaseVersionService;

    public void store(ReleaseContext releaseContext, byte[] body)
    {
        ReleaseJar jar = releaseJarRepo.find(releaseContext);
        if (jar == null)
        {
            create(releaseContext, body);
        }
        else
        {
            throw new WebApplicationException(409);
        }
    }

    public byte[] find(ReleaseContext releaseContext)
    {
        return releaseJarRepo.require(releaseContext).getJar();
    }

    public String findHash(ReleaseContext releaseContext)
    {
        switch (releaseContext.extensions().hashExt().orElseThrow())
        {
            case SHA1 ->
            {
                return releaseJarRepo.require(releaseContext).getSha1();
            }
            case MD5 ->
            {
                return releaseJarRepo.require(releaseContext).getMd5();
            }
        }
        throw new BadRequestException();
    }

    private void create(ReleaseContext releaseContext, byte[] content)
    {
        ReleaseJar releaseJar = new ReleaseJar();
        releaseJar.setReleaseVersion(releaseVersionService.findOrCreate(releaseContext));
        releaseJar.setJar(content);
        releaseJar.setMd5(DigestUtils.md5Hex(content));
        releaseJar.setSha1(DigestUtils.sha1Hex(content));
        releaseJar.setClassifier(releaseContext.classifier().orElse(null));
        releaseJar.setFilename(releaseContext.filename());
        releaseJarRepo.persist(releaseJar);
    }
}
