from corehq.apps.locations.models import SQLLocation
from custom.enikshay.exceptions import NikshayLocationNotFound, ENikshayCaseNotFound
from custom.enikshay.case_utils import get_person_case_from_episode


def _is_submission_from_test_location(case_id, owner_id):
    try:
        phi_location = SQLLocation.objects.get(location_id=owner_id)
    except SQLLocation.DoesNotExist:
        raise NikshayLocationNotFound(
            "Location with id {location_id} not found. This is the owner for person with id: {person_id}"
            .format(location_id=owner_id, person_id=case_id)
        )
    return phi_location.metadata.get('is_test', "yes") == "yes"


def is_valid_person_submission(person_case):
    return not _is_submission_from_test_location(person_case.case_id, person_case.owner_id)


def is_valid_episode_submission(episode_case):
    try:
        person_case = get_person_case_from_episode(episode_case.domain, episode_case)
    except ENikshayCaseNotFound:
        return False
    return not _is_submission_from_test_location(person_case.case_id, person_case.owner_id)


def is_valid_archived_submission(episode_case):
    try:
        person_case = get_person_case_from_episode(episode_case.domain, episode_case)
    except ENikshayCaseNotFound:
        return False
    owner_id = person_case.owner_id
    if owner_id == "_archive_":
        owner_id = person_case.dynamic_case_properties().get('last_owner', None)

    return not _is_submission_from_test_location(person_case.case_id, owner_id)

@@ -199,16 +199,75 @@
 episode%0A
+from casexml.apps.case.const import ARCHIVED_CASE_OWNER_ID%0A
 %0A%0Adef _i
@@ -1400,19 +1400,30 @@
  == 
-%22_archive_%22
+ARCHIVED_CASE_OWNER_ID
 :%0A  

use available constant for archive case