from enum import Enum
import tempfile

import pygit2

class RepoComparisonType(Enum):
    Tree = 1
    Commit = 2

def equals(repoA, repoB, test_refs, comparison_type=RepoComparisonType.Commit):
    """Compare two pygit2.Repository objects for equality

    :param pygit2.Repository repoA The first repository to compare
    :param gitubuntu.repo_builder.Repo repoB The second repository to compare
    :param list(str) test_refs String reference names that should be
        compared for equality
    :param RepoComparisonType comparison_type What underlying Git object
        should be compared for equality

    :rtype bool
    :returns Whether @repoA and @repoB contain the matching references and
    reachable Git commits
    """

    test_refs = set(test_refs)

    with tempfile.TemporaryDirectory() as tmp_dir:
        pygit2_repoB = pygit2.init_repository(tmp_dir)
        repoB.write(pygit2_repoB)

        repoA_refs = set(repoA.listall_references())
        if not test_refs.issubset(repoA_refs):
            return False
        repoA_refs = repoA_refs.intersection(test_refs)
        repoB_refs = set(pygit2_repoB.listall_references())
        if not test_refs.issubset(repoB_refs):
            return False
        repoB_refs = repoB_refs.intersection(test_refs)

        if repoA_refs.symmetric_difference(repoB_refs):
            return False

        if comparison_type == RepoComparisonType.Tree:
            peel_type = pygit2.Tree
        elif comparison_type == RepoComparisonType.Commit:
            peel_type = pygit2.Commit
        else:
            raise TypeError("Unknown RepoComparisonType: %r" % comparison_type)

        for ref in repoA_refs:
            refA_peeled = repoA.lookup_reference(ref).peel(peel_type)
            refB_peeled = pygit2_repoB.lookup_reference(ref).peel(peel_type)
            if str(refA_peeled.id) != str(refB_peeled.id):
                return False

        return True
