package dev.dinauer.maven.maven.core;

import dev.dinauer.maven.maven.core.context.ArtifactContext;
import dev.dinauer.maven.maven.core.context.VersionContext;
import dev.dinauer.maven.maven.core.model.*;
import dev.dinauer.maven.maven.core.parser.MavenMetadataUrlParser;
import dev.dinauer.maven.maven.core.parser.MavenUrlParser;
import dev.dinauer.maven.maven.shared.Extensions;
import dev.dinauer.maven.maven.shared.ParserResult;

import java.nio.file.Path;

public class MavenContextProvider
{
    public static ArtifactContext parse(String path)
    {
        ParserResult<Extensions> extensionResult = new ExtensionParser().parse(Path.of(path).getFileName().toString());
        switch (extensionResult.result().ext())
        {
            case JAR, POM ->
            {
                MavenUrlParser parser = MavenUrlParser.parse(path);
                return new VersionContext(extensionResult.result(), parser.groupId(), parser.artifactId(), extensionResult.remainder(), parser.version());
            }
            case XML ->
            {
                if (isSnapshot(path))
                {
                    MavenUrlParser parser = MavenUrlParser.parse(path);
                    return new VersionContext(extensionResult.result(), parser.groupId(), parser.artifactId(), extensionResult.remainder(), parser.version());
                }
                else
                {
                    MavenMetadataUrlParser parser = MavenMetadataUrlParser.parse(path);
                    return new ArtifactContext(extensionResult.result(), parser.groupId(), parser.artifactId(), extensionResult.remainder());
                }
            }
        }
        throw new RuntimeException();
    }

    private static boolean isSnapshot(String path)
    {
        String[] sections = path.split("/");
        return sections[sections.length - 2].endsWith("-SNAPSHOT");
    }
}
