from dateutil import parser
import logging

from django.conf import settings
from django.template.loader import render_to_string
from django.utils.text import wrap
from django.utils import translation
from django.utils.translation import ugettext_lazy as _

from .models import Case, CourtEmailCount, Court
from .encrypt import encrypt_and_store_user_data
from tasks import email_send_court, email_send_prosecutor, email_send_user


logger = logging.getLogger(__name__)


def get_plea_type(context_data):
    """
    Determine if pleas for a submission are
        all guilty  - returns "guilty"
        all not guilty - returns "not_guilty"
        or mixed - returns "mixed"
    """

    guilty_count = len([plea for plea in context_data["plea"]["data"]
                        if plea["guilty"] == "guilty"])

    if guilty_count == 0:
        return "not_guilty"
    elif guilty_count == len(context_data["plea"]["data"]):
        return "guilty"
    else:
        return "mixed"


def send_plea_email(context_data):
    """
    Sends a plea email. All addresses, content etc. are defined in
    settings.

    context_data: dict populated by form fields
    """
    try:
        court_obj = Court.objects.get_by_urn(context_data["case"]["urn"])
    except Court.DoesNotExist:
        logger.error("URN does not have a matching Court entry: {}".format(
            context_data["case"]["urn"]))
        raise

    # add DOH / name to the email subject for compliance with the current format
    if context_data["notice_type"]["sjp"] is False:
        if isinstance(context_data["case"]["date_of_hearing"], basestring):
            date_of_hearing = parser.parse(context_data["case"]["date_of_hearing"])
        else:
            date_of_hearing = context_data["case"]["date_of_hearing"]

        context_data["email_date_of_hearing"] = date_of_hearing.strftime("%Y-%m-%d")

    if context_data["case"]["plea_made_by"] == "Defendant":
        first_name = context_data["your_details"]["first_name"]
        last_name = context_data["your_details"]["last_name"]
    else:
        first_name = context_data["company_details"]["first_name"]
        last_name = context_data["company_details"]["last_name"]

    context_data["email_name"] = " ".join([last_name.upper(), first_name])

    # Add Welsh flag if journey was completed in Welsh
    if translation.get_language() == "cy":
        context_data["welsh_language"] = True

    # Get or create case
    try:
        case = Case.objects.get(urn__iexact=context_data["case"]["urn"].upper(), sent=False)
    except Case.DoesNotExist:
        case = Case(urn=context_data["case"]["urn"].upper(), sent=False)

    if context_data["notice_type"]["sjp"]:
        case.initiation_type = "J"

    case.language = translation.get_language().split("-")[0]
    case.save()

    if "court" in context_data:
        del context_data["court"]

    if getattr(settings, "STORE_USER_DATA", False):
        encrypt_and_store_user_data(case.urn, case.id, context_data)

    if not court_obj.test_mode:
        # don't add test court entries to the anon stat data
        email_count = CourtEmailCount()
        email_count.get_from_context(context_data, court=court_obj)
        email_count.save()

        email_count_id = email_count.id

    else:
        # use a fake email count ID as we're using a test record
        email_count_id = "XX"

    email_send_court.delay(case.id, email_count_id, context_data)

    if court_obj.plp_email:
        email_send_prosecutor.delay(case.id, context_data)

    email_address = context_data.get("review", {}).get("email", False)

    if not email_address:
        case.add_action("No email entered, user email not sent", "")
        return True

    data = {
        "urn": context_data["case"]["urn"],
        "plea_made_by": context_data["case"]["plea_made_by"],
        "number_of_charges": context_data["case"]["number_of_charges"],
        "plea_type": get_plea_type(context_data),
        "court_address": court_obj.court_address,
        "court_email": court_obj.court_email
    }

    email_template = "emails/user_plea_confirmation"

    try:
        if context_data["notice_type"]["sjp"]:
            email_template = "emails/user_plea_confirmation_sjp"
    except KeyError:
        pass

    html_body = render_to_string(email_template + ".html", data)
    txt_body = wrap(render_to_string(email_template + ".txt", data), 72)

    subject = _("Online plea submission confirmation")

    email_send_user.delay(case.id, email_address, subject, html_body, txt_body)

    if not court_obj.test_mode:
        case.sent = True
        email_count.sent = True
        email_count.save()

    case.save()

    return True

@@ -3704,25 +3704,18 @@
     
-    return True%0A%0A
+else:%0A    
     
@@ -3731,16 +3731,20 @@
         
+   
+ 
 %22urn%22: c
@@ -3767,24 +3767,28 @@
 e%22%5D%5B%22urn%22%5D,%0A
+    
         %22ple
@@ -3845,16 +3845,20 @@
         
+ 
+   
 %22number_
@@ -3917,24 +3917,28 @@
 %22%5D,%0A        
+  
+  
 %22plea_type%22:
@@ -3967,16 +3967,20 @@
 _data),%0A
+    
         
@@ -4025,24 +4025,28 @@
 ss,%0A        
+    
 %22court_email
@@ -4078,11 +4078,19 @@
     
+ 
-%7D%0A%0A
+   %7D%0A%0A    
     
@@ -4139,16 +4139,20 @@
 ation%22%0A%0A
+    
     try:
@@ -4156,24 +4156,28 @@
 ry:%0A        
+    
 if context_d
@@ -4195,32 +4195,36 @@
 _type%22%5D%5B%22sjp%22%5D:%0A
+    
             emai
@@ -4272,24 +4272,28 @@
 on_sjp%22%0A    
+   
+ 
 except KeyEr
@@ -4309,14 +4309,22 @@
     
+    
 pass%0A%0A
+    
     
@@ -4388,16 +4388,20 @@
 ta)%0A    
+  
+  
 txt_body
@@ -4462,16 +4462,20 @@
 ), 72)%0A%0A
+    
     subj
@@ -4518,24 +4518,28 @@
 irmation%22)%0A%0A
+    
     email_se

Fix email count not saved if user wants no email