#!/usr/bin/env python

__version__ = None  # This will be assigned later; see below
__date__ = None  # This will be assigned later; see below
__credits__ = None  # This will be assigned later; see below

try:

    from als.bcs._version import git_pieces_from_vcs as _git_pieces_from_vcs
    from als.bcs._version import run_command, register_vcs_handler
    from als.bcs._version import render as _render
    from als.bcs._version import render_pep440_auto
    from als.bcs._version import render_pep440_micro, render_pep440_develop
    from als.bcs._version import get_versions as _get_versions
    from als.bcs._version import get_config, get_keywords
    from als.bcs._version import git_versions_from_keywords
    from als.bcs._version import versions_from_parentdir
    from als.bcs._version import NotThisMethod


except ImportError:

    # Assumption is that _version.py was generated by 'versioneer.py'
    # for tarball distribution, which contains only static JSON version data

    from als.bcs._version import get_versions

    # from als.bcs._version import get_versions as _get_versions
    #
    # def get_versions():
    #     """Get version information or return default if unable to do so.
    #
    #     Extension to ._version.get_versions()
    #
    #     Additional functionality:
    #     Returns list of authors found in `git`
    #     """
    #     default_keys_values = {
    #         "version": "0+unknown",
    #         "full-revisionid": None,
    #         "dirty": None,
    #         "error": "unable to compute version",
    #         "date": None,
    #         "authors": [],
    #     }
    #
    #     return_key_values = _get_versions()
    #     return_key_values = dict(
    #         default_keys_values.items() + return_key_values.items()
    #         )
    #     return return_key_values


else:

    import os
    import sys

    def unique(seq):
        """Find unique elements in a list, without sorting

        Implementation does not depend on `numpy`
        * borrowed from https://stackoverflow.com/a/480227
        * credit to Markus Jarderot
        + https://www.peterbe.com/plog/uniqifiers-benchmark
        """
        seen = set()
        seen_add = seen.add
        return [x for x in seq if not (x in seen or seen_add(x))]

    @register_vcs_handler("git", "pieces_from_vcs")
    def git_pieces_from_vcs(
            tag_prefix, root, verbose, run_command=run_command):
        """Get version information from 'git' in the root of the source tree.

        Extension to ._version.git_pieces_from_vcs()

        Additional functionality:
        Extracts all commit authors, sorts unique authors chronologically,
        then adds them to `pieces["authors"]`, where `pieces` is the object
        that was returned by ._version.git_pieces_from_vcs()
        """
        pieces = _git_pieces_from_vcs(
            tag_prefix, root, verbose, run_command=run_command)

        GITS = ["git"]
        if sys.platform == "win32":
            GITS = ["git.cmd", "git.exe"]

        ##################################################
        # Added to retrieve list of authors
        (authors_raw, rc) = run_command(
            GITS, ["log", "--pretty=%an"], cwd=root)
        authors = [author.strip() for author in authors_raw.split('\n')]
        authors_unique = unique(authors)
        pieces["authors"] = list(reversed(authors_unique))

        return pieces


    def render(pieces, style):
        """Render the given version pieces into the requested style."""
        if pieces["error"]:
            return {"version": "unknown",
                    "full-revisionid": pieces.get("long"),
                    "dirty": None,
                    "error": pieces["error"],
                    "date": None,
                    "authors": None,
                    }

        if not style or style == "default":
            style = "pep440-auto"  # the default

        if style == "pep440-micro":
            rendered = render_pep440_micro(pieces)
        elif style == "pep440-develop":
            rendered = render_pep440_develop(pieces)
        elif style == "pep440-auto":
            rendered = render_pep440_auto(pieces)
        else:
            return_key_values = _render(pieces, style)
            return_key_values["authors"] = pieces["authors"]
            return return_key_values

        return {"version": rendered, "full-revisionid": pieces["long"],
                "dirty": pieces["dirty"], "error": None,
                "date": pieces.get("date"), "authors": pieces["authors"]}


    def get_versions():
        """Get version information or return default if unable to do so.

        Extension to ._version.get_versions()

        Additional functionality:
        Returns list of authors found in `git`
        """
        # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE.
        # If we have __file__, we can work backwards from there to the root.
        # Some py2exe/bbfreeze/non-CPython implementations don't do __file__,
        # in which case we can only use expanded keywords.

        cfg = get_config()
        verbose = cfg.verbose

        default_keys_values = {
            "version": "0+unknown",
            "full-revisionid": None,
            "dirty": None,
            "error": "unable to compute version",
            "date": None,
            "authors": [],
        }

        try:
            return git_versions_from_keywords(get_keywords(), cfg.tag_prefix,
                                              verbose)
        except NotThisMethod:
            pass

        try:
            root = os.path.realpath(__file__)
            # versionfile_source is the relative path from the top of the
            # source tree (where the .git directory might live) to this file.
            # Invert this to find the root from __file__.
            for i in cfg.versionfile_source.split('/'):
                root = os.path.dirname(root)
        except NameError:
            return default_keys_values

        try:
            pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose)
            return render(pieces, cfg.style)
        except NotThisMethod:
            pass

        try:
            if cfg.parentdir_prefix:
                return versions_from_parentdir(
                    cfg.parentdir_prefix, root, verbose)
        except NotThisMethod:
            pass

        return_key_values = _get_versions()
        return_key_values = dict(
            list( default_keys_values.items() )
            + list( return_key_values.items() )
            )
        return return_key_values


__version__ = get_versions()["version"]
__date__ = get_versions()["date"]
__credits__ = get_versions()["authors"]

del get_versions
