from django.core.exceptions import ObjectDoesNotExist

from db.models.repos import CodeReference, ExternalRepo


def get_internal_code_reference(instance, commit=None):
    project = instance.project

    if not project.has_code:
        return None

    repo = project.repo

    if commit:
        try:
            return CodeReference.objects.get(repo=repo, commit=commit)
        except ObjectDoesNotExist:
            return None

    # If no commit is provided we get the last commit, and save new ref if not found
    last_commit = repo.last_commit
    if not last_commit:
        return None

    code_reference, _ = CodeReference.objects.get_or_create(repo=repo, commit=last_commit[0])
    return code_reference


def get_external_code_reference(instance, external_repo, commit=None):
    project = instance.project

    external_repo, created = ExternalRepo.objects.get_or_create(project=project,
                                                                git_url=external_repo)

    code_reference, _ = CodeReference.objects.get_or_create(external_repo=external_repo,
                                                            commit=commit)
    return code_reference


def assign_code_reference(instance, commit=None):
    if instance.code_reference is not None:
        return
    build = instance.specification.build if instance.specification else None
    if not commit and build:
        commit = build.commit
    external_repo = build.git if build and build.git else None
    if external_repo:
        code_reference = get_external_code_reference(instance=instance,
                                                     external_repo=external_repo,
                                                     commit=commit)
    else:
        code_reference = get_internal_code_reference(instance=instance,
                                                     commit=commit)
    if code_reference:
        instance.code_reference = code_reference

    return instance

@@ -841,15 +841,9 @@
 po, 
-created
+_
  = E
@@ -896,72 +896,8 @@
 ect,
-%0A                                                               
  git
@@ -916,17 +916,16 @@
 l_repo)%0A
-%0A
     code

Fix prospector