package com.atlassian.bitbucket.internal.branch.model.version;

import com.atlassian.bitbucket.internal.branch.model.exception.IllegalVersionStringException;
import com.google.common.base.MoreObjects;
import org.apache.commons.lang3.StringUtils;

import javax.annotation.Nonnull;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;

import static com.atlassian.bitbucket.util.Chainable.chain;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;

/**
 * Representation of a generic branch version that a branch name can signify.
 *
 * @since 2.8
 */
public class BranchVersion implements Comparable<BranchVersion> {

    private final String original;
    private final List<Component> components;
    private final int firstNumeric;

    private BranchVersion(String original, List<Component> components) {
        this.original = original;
        this.components = components;
        this.firstNumeric = findFirstNumeric();

        if (firstNumeric == -1) {
            throw new IllegalVersionStringException("'" + original + "' does not contain a version");
        }
    }

    /**
     * Parse branch version from a string.
     *
     * @param versionString string representing the version
     * @param versionComponentSeparators a regular expression representing characters to use as separators for
     *                                   the version components. E.g. [-_\.] would result in either of '-', '_' or '.'
     *                                   being used as a separator, in which case a version string 'abc_1.2-final'
     *                                   would be parsed into 4 components: 'abc', '1', '2' and 'final'
     * @return a {@code BranchVersion} object representing {@code versionString}
     */
    @Nonnull
    public static BranchVersion parse(@Nonnull String versionString, @Nonnull String versionComponentSeparators) {
        checkNotNull(versionComponentSeparators, "versionComponentSeparators");
        String[] components = checkNotNull(versionString, "versionString").split(versionComponentSeparators);
        return new BranchVersion(versionString, chain(components)
                .filter(StringUtils::isNotBlank)
                .transform(Component.FROM_CONTENT)
                .toList());
    }

    /**
     * Compare this version to {@code that}.
     *
     * @param that the other version to compare
     * @return {@inheritDoc}
     * @throws IllegalArgumentException if the versions are not {@link #isCompatibleWith(BranchVersion) compatible}
     */
    @Override
    public int compareTo(@Nonnull BranchVersion that) {
        if (!isCompatibleWith(that)) {
            throw new IllegalArgumentException(this + "is not compatible to " + that);
        }
        int max = Math.min(components.size(), that.components.size());
        for (int i = firstNumeric; i < max; i++) {
            int result = componentAt(i).compareTo(that.componentAt(i));
            if (result != 0) {
                return result;
            }
        }
        // check if count of components is different
        int bySize = Integer.compare(components.size(), that.components.size());
        if (bySize != 0) {
            if (findComponentAt(max, that).isNumeric()) {
                // the extra component is numeric - containing version is higher
                return bySize;
            } else {
                // the extra component is non-numeric - containing version is lower
                return -bySize;
            }
        }
        // all things equal, fall back to stringwise comparison
        return original.compareTo(that.original);
    }

    @Nonnull
    public Predicate<BranchVersion> matcher() {
        return BranchVersion.this::isCompatibleWith;
    }

    /**
     * Check, whether {@code that} is compatible with this version. Two versions are compatible when all the components
     * before the first numeric components are equal. Compatible versions form an ordered path. Non-compatible versions
     * cannot be {@link #compareTo(BranchVersion) compared}.
     *
     * @param that the branch version to check
     * @return {@code true}, if this version is compatible with {@code that}, {@code false} otherwise
     */
    public boolean isCompatibleWith(@Nonnull BranchVersion that) {
        if (firstNumeric != that.firstNumeric) {
            return false;
        }
        int componentsToCompare = firstNumeric >= 0 ? firstNumeric : components.size();
        for (int i = 0; i < componentsToCompare; i++) {
            if (componentAt(i).compareTo(that.componentAt(i)) != 0) {
                return false;
            }
        }
        return true;
    }

    @Override
    public int hashCode() {
        return original.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (!getClass().equals(obj.getClass())) {
            return false;
        }
        BranchVersion that = (BranchVersion) obj;
        // consistent with compareTo
        return original.equals(that.original);
    }

    @Override
    public String toString() {
        return MoreObjects.toStringHelper(this)
                .add("original", original)
                .add("components", components)
                .toString();
    }

    private int findFirstNumeric() {
        for (int i = 0; i < components.size(); i++) {
            if (components.get(i).isNumeric()) {
                return i;
            }
        }
        return -1;
    }

    private Component componentAt(int i) {
        return components.get(i);
    }

    private Component findComponentAt(int i, BranchVersion that) {
        if (components.size() > i) {
            return componentAt(i);
        } else {
            return that.componentAt(i);
        }
    }

    private static class Component implements Comparable<Component> {

        static final Function<String, Component> FROM_CONTENT = Component::new;

        private final String content;
        private final Integer numericContent;
        private final boolean isNumeric;

        private Component(@Nonnull String content) {
            checkArgument(StringUtils.isNotBlank(content), "Content cannot be blank");
            this.content = content;
            this.numericContent = parseNumeric(content);
            this.isNumeric = numericContent != null;
        }

        private Integer parseNumeric(String content) {
            try {
                return Integer.valueOf(content);
            } catch (NumberFormatException e) {
                return null;
            }
        }

        boolean isNumeric() {
            return isNumeric;
        }

        @Override
        public int compareTo(@Nonnull Component that) {
            if (this.isNumeric && that.isNumeric) {
                return this.numericContent.compareTo(that.numericContent);
            } else if (this.isNumeric) {
                // numbers take precedence over non-numbers
                return 1;
            } else if (that.isNumeric) {
                // numbers take precedence over non-numbers
                return -1;
            } else {
                // both non-numeric
                return this.content.compareTo(that.content);
            }
        }

        public boolean equals(Object obj) {
            if (obj == null) {
                return false;
            }
            if (!getClass().equals(obj.getClass())) {
                return false;
            }
            Component that = (Component) obj;
            return this.compareTo(that) == 0;
        }

        @Override
        public int hashCode() {
            return content.hashCode();
        }

        @Override
        public String toString() {
            return content;
        }
    }
}
