from datetime import datetime, timedelta, date
import hashlib
from django.contrib.auth.models import User
import random
import uuid

from ashandapp.models import CareTeam,ProviderRole,ProviderLink, CaregiverLink, CareRelationship
from patient.models import Patient, IdentifierType, PatientIdentifier
from provider.models import Provider

from django.db import transaction


@transaction.commit_manually
def create_user(username='mockuser', password='demouser', firstname=None, lastname=None):    
    transaction.commit()
    try:
        return User.objects.get(username=username)
    except:
 
        user = User()    
        user.username = username
        user.first_name = firstname
        user.last_name=lastname
        user.email = '%s_%s@carehq.com' % (firstname, lastname)
        user.set_password(password)
        user.save()
        transaction.commit()
        return user
        
@transaction.commit_manually
def create_provider(firstname, lastname, job_title, affiliation):
    firstclean = firstname.replace("'","")
    lastclean = lastname.replace("'","")
    prov = Provider()
    prov.job_title = job_title
    prov.affiliation = affiliation    
    prov.user = create_user(username=firstclean.lower() + "_" + lastclean.lower(), password='demo', firstname=firstname, lastname = lastname)
    prov.save()
    transaction.commit()
    return prov

@transaction.commit_manually
def create_or_get_provider_role(is_primary=False):
    #set some random role.
    if is_primary:
        role = 'nurse-triage'
    else:
        role = ProviderRole.ROLE_CHOICES[random.randint(0, len(ProviderRole.ROLE_CHOICES)-1)][0]

    provider_role = ProviderRole()
    provider_role.role = role 
    provider_role.role_description = "unique instance %s" % (uuid.uuid1().hex)
    provider_role.role_notes = "autogenerated from demo_load"
    provider_role.save()
    transaction.commit()
    return provider_role
    

#@transaction.commit_manually
def create_caregiver(firstname, middlename, lastname, sex):
    """Just get or create a new user for a caregiver's given name"""    
    firstclean = firstname.replace("'","")
    lastclean = lastname.replace("'","")
    dob = date(random.randint(1955,2008), random.randint(1,12), random.randint(1,28))
    
    username=firstclean.lower() + "_" + lastclean.lower()
    try:
        return User.objects.get(username = username)
    except:
        user = create_user(username=username, password='demo', firstname=firstname, lastname=lastname)
        transaction.commit()        
    return user


@transaction.commit_manually
def create_patient(firstname, middlename, lastname, sex):    
    try:
        usr = User.objects.get(first_name=firstname, last_name=lastname)
        return Patient.objects.get(user=usr) 
    except Exception, e:
        firstclean = firstname.replace("'","")
        lastclean = lastname.replace("'","")            
        
        dob = date(random.randint(1955,2008), random.randint(1,12), random.randint(1,28))            
        pt = Patient()    
        pt.sex = sex
        pt.dob = dob
        
        pt.user = create_user(username=firstclean.lower() + "_" + lastclean.lower(), password='demo', firstname=firstname, lastname=lastname)
        
        pt.is_primary = True
        
        pt.save()
        transaction.commit()
    
        return pt


def set_random_identifiers(patient):
    for ident in IdentifierType.objects.all():
        if random.random() < 0.33:
            #set some arbitrary somewhat random threshold to skip
            continue
        new_id = PatientIdentifier()
        new_id.id_type = ident
        new_id.patient = patient
        new_id.id_value = uuid.uuid1().hex
        new_id.save()
