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

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

import java.util.List;
import java.util.OptionalInt;
import java.util.stream.IntStream;

public class SnapshotFileParser
{
    public static SnapshotFile parse(String artifactId, String version, String raw)
    {
        ExtensionParser.Result extensionResult = ExtensionParser.parse(raw);

        SnapshotFile file = new SnapshotFile();

        file.setBase(extensionResult.base());
        file.setType(extensionResult.ext());
        file.setHash(extensionResult.hashExt());

        file.setRaw(raw);
        file.setArtifactId(artifactId);
        file.setVersion(version);

        String dataString = prepareForData(artifactId, version, raw);
        file.setDate(getDate(dataString));

        String timeString = prepareForTime(dataString);
        file.setTime(getTime(timeString));

        String buildNumberString = prepareForBuildNumber(timeString);
        file.setBuildNumber(getBuildNumber(buildNumberString));

        return file;
    }

    private static String prepareForData(String artifact, String version, String raw)
    {
        return Strings.CI.removeStart(raw, String.format("%s-%s-", artifact, prepareVersion(version)));
    }

    private static String prepareForTime(String path)
    {
        return Strings.CI.removeStart(path.substring(9), ".");
    }

    private static String prepareForBuildNumber(String path)
    {
        return Strings.CI.removeStart(path.substring(7), "-");
    }

    private static int getBuildNumber(String path)
    {
        int nextDot = path.indexOf(".");
        int nextDash = path.indexOf("-");
        OptionalInt optInt = IntStream.of(nextDash, nextDot).filter(index -> index > 0).min();
        if (optInt.isPresent())
        {
            return Integer.parseInt(path.substring(0, optInt.getAsInt()));
        }
        throw new IllegalArgumentException();
    }

    private static String getDate(String path)
    {
        return path.substring(0, 8);
    }

    private static String getTime(String path)
    {
        return path.substring(0, 6);
    }

    private static String prepareVersion(String version)
    {
        return Strings.CI.removeEnd(version, "-SNAPSHOT");
    }
}
