from collections import namedtuple
import copy
import functools
import logging
import re
import sys
from gitubuntu.source_information import (
    GitUbuntuSourceInformation,
    NoPublicationHistoryException,
)

import debian
# This effectively declares an interface for the type of Version
# object we want to use in the git-ubuntu code
from debian.debian_support import NativeVersion as Version
import pytest

__all__ = [
   "next_development_version_string",
   "next_sru_version_string",
   "version_compare",
   "split_version_string",
]

# see _decompose_version_string for explanation of members
_VersionComps = namedtuple(
    "_VersionComps",
    ["prefix_parts", "ubuntu_maj", "ubuntu_series", "ubuntu_other", "ubuntu_min"]
)


def _get_version_parts(version_string):
    """Return a list of separated string parts of a version string

    Simply breaks a string into its component substrings

    Raises a ValueError if both 'ubuntu' and 'build' are in
    version_string.
    """
    parts = [
        part
        for part in
        Version.re_all_digits_or_not.findall(version_string)
    ]
    if 'build' in parts and 'ubuntu' in parts:
        raise ValueError("Not sure how to decompose %s: both build and "
            "ubuntu found" % version_string
        )
    return parts

def _decompose_version_string(version_string):
    """Return the "Ubuntu"-relevant components of a version string

    Returns a _VersionComps namedtuple, throwing away some information.

    prefix_parts is a list of separated string parts forming the first
    "non-Ubuntu" part of the string, to which Ubuntu-specific version parts
    might be appended. This excludes any "build" and subsequent parts, as they
    are not relevant to version bumping. This also excludes any "ubuntu" and
    subseqent parts, as the necessary information there is encoded using
    ubuntu_maj and ubuntu_min instead.

    ubuntu_maj is the "major" Ubuntu version number as an integer, or None if
    not present. For example, in the version strings "1.0-2ubuntu3" and
    "1.0-2ubuntu3.4", 3 is the major Ubuntu version number in both cases. In
    "1.0-2", the major Ubuntu version number is not present.

    ubuntu_series is the "series" in the Ubuntu version number as a string, or
    None if not present. For example, in the version string
    "1.0.2ubuntu3.17.04.4", 17.04 is the Ubuntu series string. In both
    "1.0-2ubuntu3.4" and "1.0-2", the Ubuntu series is not present.

    ubuntu_other is any non-series information as a string between the
    major and minor version numbers. For example, in the version strings
    "1.0-2ubuntu3.4" and "1.0-2ubuntu3.17.04.4", the other Ubuntu
    version string is not present. In both "1.0-2" and "1.0-2ubuntu3",
    the other Ubuntu version number is not present. In
    "1.2.2-0ubuntu13.1.23", "1" is the Ubuntu other version string.

    ubuntu_min is the "minor" Ubuntu version number as an integer, or None if
    not present. For example, in the version strings "1.0-2ubuntu3.4" and
    "1.0-2ubuntu3.17.04.4", 4 is the Ubuntu minor version number. In both
    "1.0-2" and "1.0-2ubuntu3", the minor Ubuntu version number is not
    present. In "1.2.2-0ubuntu13.1.23", 23 is the Ubuntu minor version
    number.

    For version strings not following these standard forms, the result is
    undefined except where specific test cases exist for them.
    """

    parts = _get_version_parts(version_string)
    if 'build' in parts:
        return _VersionComps._make(
            [parts[:parts.index('build')], None, None, None, None]
        )
    elif 'ubuntu' in parts:
        ubuntu_idx = parts.index('ubuntu')
        static_parts = parts[:ubuntu_idx]
        suffix_parts = parts[ubuntu_idx+1:]
        try:
            ubuntu_maj = int(suffix_parts[0])
        except IndexError:
            # nothing after "Xubuntu", treated as 1
            ubuntu_maj = 1
        ubuntu_series = None
        ubuntu_other = None
        if len(suffix_parts) < 2:
            ubuntu_min = None
        else:
            try:
                ubuntu_min = int(suffix_parts[-1])
            except ValueError:
                ubuntu_min = None
            if len(suffix_parts[1:-1]) > 2:
                ubuntu_series = ''.join(suffix_parts[2:-2])
                if not re.match(r'\d\d\.\d\d', ubuntu_series):
                    ubuntu_series = None
                    ubuntu_other = ''.join(suffix_parts[2:-2])
        return _VersionComps._make(
            [static_parts, ubuntu_maj, ubuntu_series, ubuntu_other, ubuntu_min]
        )
    else:
        return _VersionComps._make([parts, None, None, None, None])


def split_version_string(version_string):
    """Return the Debian version and Ubuntu suffix, if present

    For example:
        "1.0-2ubuntu3" -> Debian version = "1.0-2", Ubuntu suffix = "ubuntu3"
        "1.0-2ubuntu3.4" -> Debian version = "1.0-2", Ubuntu suffix = "ubuntu3.4"
        "1.0-2build1" -> Debian version = "1.0-2", Ubuntu suffix = "build1"
        "1.0-2" -> Debian version = "1.0-2", Ubuntu suffix = ""

    Since the callers use of the version string is not always known,
    return the list of strings as provided by _decompose_version_string.

    Returns a 2-tuple of lists of strings
    """
    parts = _get_version_parts(version_string)

    if 'build' in parts:
        return (
            parts[:parts.index('build')],
            parts[parts.index('build'):],
        )

    if 'ubuntu' in parts:
        return (
            parts[:parts.index('ubuntu')],
            parts[parts.index('ubuntu'):],
        )

    return (
        parts,
        [],
    )


def _bump_version_object(old_version_object, bump_function):
    """Return a new Version object with the correct attribute bumped

    Native packages need to have their debian_version bumped; conversely
    non-native packages need to have their upstream_version bumped with their
    debian_version staying the same. The bumping mechanism is the same either
    way. This function handles this by working out which is needed, calling
    bump_function with the old version suffix to return a bumped attribute
    suffix, and creating a new Version object with the required attributed
    bumped accordingly.
    """

    if old_version_object.debian_version is None:
        bump_attr = 'upstream_version'
    else:
        bump_attr = 'debian_version'

    old_version_suffix = getattr(old_version_object, bump_attr)
    # While we are only bumping a specific suffix, we need to know the
    # entire version for SRU version testing
    new_version_suffix = bump_function(old_version_object, old_version_suffix)
    new_version_object = copy.deepcopy(old_version_object)
    setattr(new_version_object, bump_attr, new_version_suffix)
    return new_version_object


def _bump_development_version_suffix_string(version, version_suffix_string):
    """Return the next development version suffix

    Keeping the static components the same, bump the Ubuntu major
    version (see _decompose_version_string for definitions of these terms)
    and drop any minors.
    """

    old_suffix_comps = _decompose_version_string(version_suffix_string)

    new_ubuntu_maj = 1 if old_suffix_comps.ubuntu_maj is None else old_suffix_comps.ubuntu_maj + 1
    new_suffix_comps = old_suffix_comps.prefix_parts + ['ubuntu', str(new_ubuntu_maj)]

    return ''.join(new_suffix_comps)


def _bump_sru_version_suffix_string(befores, series_string, afters,
    version, version_suffix_string
):
    """Return the next SRU version suffix

    Keeping the static components the same, maintain the same major (or
    set it to 0 if the first major) and bump the minor. Keep the series
    string (e.g., 16.04) in the version, if it was present before.
    """

    befores_comps = [_decompose_version_string(str(v)) for v in befores]
    afters_comps = [_decompose_version_string(str(v)) for v in afters]
    old_suffix_comps = _decompose_version_string(version_suffix_string)
    old_version_comps = _decompose_version_string(str(version))

    new_maj = 0 if old_suffix_comps.ubuntu_maj is None else old_suffix_comps.ubuntu_maj
    new_min = 1 if old_suffix_comps.ubuntu_min is None else old_suffix_comps.ubuntu_min + 1

    bumped_parts = ['ubuntu', str(new_maj), '.']
    if old_suffix_comps.ubuntu_series:
        bumped_parts.extend([old_suffix_comps.ubuntu_series, '.'])
    elif old_suffix_comps.ubuntu_other:
        bumped_parts.extend([old_suffix_comps.ubuntu_other, '.'])
    elif str(version) in [str(v) for v in befores + afters]:
        bumped_parts.extend([series_string, '.'])
    elif any(
        v.prefix_parts + ['ubuntu', str(v.ubuntu_maj), '.'] == old_version_comps.prefix_parts + bumped_parts
        for v in befores_comps + afters_comps
    ):
        bumped_parts.extend([series_string, '.'])
    bumped_parts.append(str(new_min))

    return ''.join(old_suffix_comps.prefix_parts + bumped_parts)


def next_development_version_string(version_string):
    """Return the next development version relative to @version_string
    """
    return str(_bump_version_object(
        Version(version_string),
        _bump_development_version_suffix_string
    ))


def _next_sru_version(befores, series_string, current, afters):
    """Return the next SRU version respecting other series information
    """
    return _bump_version_object(current,
        functools.partial(
            _bump_sru_version_suffix_string,
            befores,
            series_string,
            afters
        )
    )


def max_version(lp_series_object, pkgname):
    """Return the latest published version for a given source package
    and series
    """
    ubuntu_source_information = GitUbuntuSourceInformation('ubuntu', pkgname)
    try:
        for spi in ubuntu_source_information.launchpad_versions_published(
            sorted_by_version=True, series=lp_series_object
        ):
            return Version(spi.version)
    except NoPublicationHistoryException:
        return None


def next_sru_version_string(lp_series_object, pkgname):
    """Return the next SRU version for a given source package and series

    Queries Launchpad for publishing information about other active
    series for the same source package.
    """
    # for a series extract the required parameters
    ubuntu_source_information = GitUbuntuSourceInformation('ubuntu')
    active_series_objects = ubuntu_source_information.active_series
    befores = [max_version(before_series_object, pkgname)
        for before_series_object in active_series_objects
        if float(before_series_object.version) < float(lp_series_object.version)
    ]
    afters = [max_version(after_series_object, pkgname)
        for after_series_object in active_series_objects
        if float(after_series_object.version) > float(lp_series_object.version)
    ]
    current = max_version(lp_series_object, pkgname)
    return str(_next_sru_version(
        befores,
        str(lp_series_object.version),
        current,
        afters
    ))


def version_compare(a, b):
    if a is None:
        if b is None:
            return 0
        return -1
    if b is None:
        return 1
    return debian.debian_support.version_compare(a, b)


@pytest.mark.parametrize('test_input, expected', [
    ('2', _VersionComps._make([['2'], None, None, None, None])),
    ('2ubuntu1', _VersionComps._make([['2'], 1, None, None, None])),
    ('2ubuntu1.3', _VersionComps._make([['2'], 1, None, None, 3])),
    ('2ubuntu0.16.04.3', _VersionComps._make([['2'], 0, '16.04', None, 3])),
    ('2build1', _VersionComps._make([['2'], None, None, None, None])),
    ('2build1.3', _VersionComps._make([['2'], None, None, None, None])),
    ('0ubuntu13.1.22', _VersionComps._make([['0'], 13, None, '1', 22])),
])
def test_decompose_version_string(test_input, expected):
    assert _decompose_version_string(test_input) == expected


@pytest.mark.parametrize('test_input, expected', [
    ('1.0-2', (['1', '.', '0', '-', '2'], [])),
    ('1.0-2ubuntu1', (['1', '.', '0', '-', '2'], ['ubuntu', '1'])),
    ('1.0-2ubuntu1.3', (['1', '.', '0', '-', '2'], ['ubuntu', '1', '.', '3'])),
    ('1.0-2build1', (['1', '.', '0', '-', '2'], ['build', '1'])),
    ('1.0-2builder1', (['1', '.', '0', '-', '2', 'builder', '1'], [])),
    ('1', (['1'], [])),
    ('1ubuntu2', (['1'], ['ubuntu', '2'])),
    ('1.0-3ubuntu', (['1', '.', '0', '-', '3'], ['ubuntu'])),
    ('1:1.0-1.1ubuntu1', (['1', ':', '1', '.', '0', '-', '1', '.', '1'], ['ubuntu', '1'])),
])
def test_split_version_string(test_input, expected):
    assert split_version_string(test_input) == expected

@pytest.mark.parametrize('test_input, expected', [
    ('1.0-2', '1.0-2ubuntu1'),
    ('1.0-2ubuntu1', '1.0-2ubuntu2'),
    ('1.0-2ubuntu1.3', '1.0-2ubuntu2'),
    ('1.0-2ubuntu2', '1.0-2ubuntu3'),
    ('1.0-2build1', '1.0-2ubuntu1'),
    ('1', '1ubuntu1'),
    ('1ubuntu2', '1ubuntu3'),
    ('1.0-3ubuntu', '1.0-3ubuntu2'),
])
def test_next_development_version_string(test_input, expected):
    assert next_development_version_string(test_input) == expected


@pytest.mark.parametrize('befores, series_string, current, afters, expected', [
    ([], '16.04', '1.0-1', [], '1.0-1ubuntu0.1'),
    (['1.0-1'], '16.04', '1.0-1', [], '1.0-1ubuntu0.16.04.1'),
    ([], '16.04', '1.0-1', ['1.0-1'], '1.0-1ubuntu0.16.04.1'),
    (['1.0-1ubuntu1'], '16.04', '1.0-1ubuntu1', [], '1.0-1ubuntu1.16.04.1'),
    ([], '16.04', '1.0-1ubuntu1', ['1.0-1ubuntu1'], '1.0-1ubuntu1.16.04.1'),
    (['1.0-1ubuntu1'], '16.04', '1.0-1ubuntu1', ['1.0.1-ubuntu1'], '1.0-1ubuntu1.16.04.1'),
    (['1.0-1ubuntu1'], '16.04', '1.0-1ubuntu1', ['1.0.1-ubuntu2'], '1.0-1ubuntu1.16.04.1'),
    (['1.0-1ubuntu1.14.04.1'], '16.04', '1.0-1ubuntu1.16.04.1', ['1.0-1ubuntu1.17.10.1'], '1.0-1ubuntu1.16.04.2'),
    (['1.0-1ubuntu1.14.04.1'], '16.04', '1.0-1ubuntu1', ['1.0-1ubuntu2'], '1.0-1ubuntu1.16.04.1'),
    (['1.0-1ubuntu1.14.04.1'], '16.04', '1.0-1ubuntu1', ['1.0-1ubuntu1.17.10.1'], '1.0-1ubuntu1.16.04.1'),
    (['1.0-1'], '16.04', '1.0-1ubuntu1', ['1.0-1ubuntu11'], '1.0-1ubuntu1.1'),
    (['1.0-1'], '16.04', '1.0-2ubuntu1', ['1.0-2ubuntu11'], '1.0-2ubuntu1.1'),
    ([], '16.04', '1.0-2ubuntu1', ['2.0-2ubuntu1'], '1.0-2ubuntu1.1'),
    (['1.0.1-0ubuntu0.16.04.1', None, None,], '17.04', '1.0.1-0ubuntu1', ['1.0.1-1ubuntu2', '1.0.1-1ubuntu2',], '1.0.1-0ubuntu1.1'),
    ([None, None,], '17.04', '1.0.1-0ubuntu1', ['1.0.1-1ubuntu2', '1.0.1-1ubuntu2',], '1.0.1-0ubuntu1.1'),
    ([None, None,], '17.04', '1.0.1-0ubuntu1', [None, None,], '1.0.1-0ubuntu1.1'),
])
def test__next_sru_version(befores, series_string, current, afters, expected):
    assert _next_sru_version(
        befores=[Version(vstr) for vstr in befores],
        series_string=series_string,
        current=Version(current),
        afters=[Version(vstr) for vstr in afters],
    ) == expected


@pytest.mark.parametrize('a, b, expected', [
    (None, '1.0-1', -1),
    (None, None, 0),
    ('1.0-1', None, 1),
    ('1.0-1', '1.0-1ubuntu1', -1),
    ('1.0-1ubuntu1', '1.0-1ubuntu1', 0),
    ('1.0-1ubuntu1', '2.0-1', -1),
    ('1.0-1ubuntu1', '1.0-2', -1),
])
def test_version_compare(a, b, expected):
    assert version_compare(a, b) == expected
