package dev.dinauer.maven.maven.core.snapshot.parser;

import dev.dinauer.maven.maven.core.snapshot.SnapshotFile;
import dev.dinauer.maven.maven.shared.Parser;
import dev.dinauer.maven.maven.shared.ParserResult;
import org.apache.commons.lang3.Strings;

import java.util.List;

public class SnapshotFileParser implements Parser<SnapshotFile>
{
    private final String groupId;
    private final String artifactId;

    public SnapshotFileParser(String groupId, String artifactId)
    {
        this.groupId = groupId;
        this.artifactId = artifactId;
    }

    @Override
    public ParserResult<SnapshotFile> parse(String input)
    {
        String withoutGroupAndArtifact = dropGroupAndArtifact(input);
        String[] sections = withoutGroupAndArtifact.split("-");
        if (sections.length >= 2)
        {
            String[] dateTime = sections[0].split("\\.");
            if (dateTime.length == 2)
            {
                SnapshotFile file = new SnapshotFile();
                file.setDate(dateTime[0]);
                file.setTime(dateTime[1]);
                file.setBuildNumber(Integer.parseInt(sections[1]));
                if (sections.length >= 3)
                {
                    String classifier = String.join("-", List.of(sections).subList(2, sections.length));
                    file.setClassifier(classifier);
                }
                return new ParserResult<>(null, file);
            }
        }
        throw new IllegalArgumentException();
    }

    private String dropGroupAndArtifact(String input)
    {
        return Strings.CI.removeStart(input, String.format("%s-%s-", groupId, artifactId));
    }
}