from django.utils.translation import ugettext as _
from casexml.apps.case.xml import V2
from casexml.apps.phone.restore import RestoreConfig, RestoreParams
from corehq.apps.domain.models import Domain
from dimagi.utils.logging import notify_exception

from .models import DemoUserRestore


def turn_off_demo_mode(commcare_user):
    """
    Turns demo mode OFF for commcare_user and deletes existing demo restore
    """

    # delete old restore
    old_restore_id = commcare_user.demo_restore_id
    if old_restore_id:
        old_restore = DemoUserRestore.objects.get(id=old_restore_id)
        old_restore.delete()

    commcare_user.demo_restore_id = None
    commcare_user.is_demo_user = False
    commcare_user.save()


def turn_on_demo_mode(commcare_user, domain):
    """
    Turns demo mode ON for commcare_user, and resets restore to latest
    """
    try:
        # the order of following two is important, because the restore XML should contain...
        # user_type='demo' in user_data element
        commcare_user.is_demo_user = True
        reset_demo_user_restore(commcare_user, domain)
    except Exception as e:
        notify_exception(None, message=e.message)
        return {'errors': [
            _("Something went wrong in creating restore for the user. Please try again or report an issue")
        ]}
    else:
        commcare_user.save()
        return {'errors': []}


def reset_demo_user_restore(commcare_user, domain):
    """
    Updates demo restore for the demo commcare_user
    """
    assert commcare_user.domain == domain

    # get latest restore
    restore = RestoreConfig(
        project=Domain.get_by_name(domain),
        user=commcare_user.to_casexml_user(),
        params=RestoreParams(version=V2),
    ).get_payload().as_file()
    demo_restore = DemoUserRestore.create(commcare_user._id, restore)

    # set reference to new restore
    commcare_user.demo_restore_id = demo_restore.id


def demo_user_restore_response(commcare_user):
    # Todo handle case where user is in demo-mode, but demo restore is not set due to task fail
    assert commcare_user.is_commcare_user()

    restore = DemoUserRestore.objects.get(id=commcare_user.demo_restore_id)
    return restore.get_restore_http_response()

@@ -422,203 +422,53 @@
 %0A   
- #
  delete
- old restore%0A    old_restore_id = commcare_user.demo_restore_id%0A    if old_restore_id:%0A        old_restore = DemoUserRestore.objects.get(id=old_restore_id)%0A        old_restore.delete(
+_demo_restore_for_user(commcare_user
 )%0A
-%0A
     
@@ -791,22 +791,20 @@
 XML 
-should
+will
  contain
 ...%0A
@@ -803,11 +803,8 @@
 tain
-...
 %0A   
@@ -809,16 +809,22 @@
        #
+ %3Cdata
  user_ty
@@ -836,29 +836,52 @@
 emo'
- in user_data element
+%3E only if commcare_user.is_demo_user is True
 %0A   
@@ -974,16 +974,46 @@
 domain)%0A
+        return %7B'errors': %5B%5D%7D%0A
     exce
@@ -1232,77 +1232,8 @@
  %5D%7D%0A
-    else:%0A        commcare_user.save()%0A        return %7B'errors': %5B%5D%7D%0A
 %0A%0Ade
@@ -1393,16 +1393,111 @@
 domain%0A%0A
+    # if there is a restore already, delete it%0A    delete_demo_restore_for_user(commcare_user)%0A
     # ge
@@ -1806,24 +1806,24 @@
 new restore%0A
-
     commcare
@@ -1862,16 +1862,355 @@
 tore.id%0A
+    commcare_user.save()%0A%0A%0Adef delete_demo_restore_for_user(commcare_user):%0A    # Deletes the users' current demo restore object%0A    # Caller should save the user doc%0A    old_restore_id = commcare_user.demo_restore_id%0A    if old_restore_id:%0A        old_restore = DemoUserRestore.objects.get(id=old_restore_id)%0A        old_restore.delete()%0A
 %0A%0Adef de

save user object correctly; delete old restore when resetting