def bg_validator(omhe_value):
    """validate blood glucose"""
    valdict={}

    if omhe_value.isdigit():
        if float(omhe_value)>=0 and float(omhe_value)<=400:
            valdict['bg_numeric']=omhe_value
            return valdict
        else:
            raise InvalidValueError("The Blood glucose number should be in range:0-400")

    raise InvalidValueError("You didn't supply a number for blood pressure") def bp_validator(omhe_value):
    val_dict={}
    """bp_validator"""

    if omhe_value.isdigit() and len(omhe_value)==9:
        bp_systolic=omhe_value[0:3]
        bp_diastolic=omhe_value[3:6]
        bp_pulse=omhe_value[6:9]
        valdict={'bp_systolic':bp_systolic,
                'bp_diastolic':bp_diastolic,
                'bp_pulse':bp_pulse,}
        return valdict
    
    if omhe_value.__contains__('/'):
        sys_delin='/'
    elif omhe_value.__contains__('d'):
        sys_delin='d'
    else:  
        raise InvalidValueError, "Invalid bp syntax"
        error_additional_info
    
    splstr1=omhe_value.split(sys_delin)
    if len(splstr1) !=2:
        raise InvalidValueError, "Invalid bp syntax"
    bp_systolic=splstr1[0]

    if bp_systolic.isdigit()==False:
        raise InvalidValueError, "Systolic value is not a number"
    
    if ( 20 > int(bp_systolic)) or (int(bp_systolic) > 500):
        raise InvalidValueError, "Systolic value is out of range"
    
    
    splstr2=splstr1[1].split('p')
    bp_diastolic=splstr2[0]

    if bp_diastolic.isdigit()==False:
        raise InvalidValueError, "Diastolic value not a number"
    elif (20 > int(bp_diastolic)) or (int(bp_diastolic)> 500):
        raise InvalidValueError, "Diastolic value out of range"
    valdict={
            'bp_systolic':bp_systolic,
            'bp_diastolic':bp_diastolic,
            }
    if len(splstr2)==2:
        """Get the pulse if provided"""
        bp_pulse=splstr2[1]
        if bp_pulse.isdigit()==False:
            raise InvalidValueError, "Pulse not a number"
        elif (10 > int(bp_pulse)) or (int(bp_pulse) > 500):
            raise InvalidValueError, "Pulse value out of range"
        valdict['bp_pulse']=bp_pulse
            
    return valdict def sbp_validator(omhe_value):
    valdict={}
    if validateEmail(omhe_value):
        valdict['sbp_to']=omhe_value
    else:
        error_msg="The email address '%s'did not validate." % (omhe_value)
        raise InvalidValueError(error_msg)

    return valdict def st_validator(omhe_value):
    """validate steps"""
    valdict={}
    
    if omhe_value.isdigit():
        valdict['st_numeric']=omhe_value
    try:
        x=float(valdict['st_numeric'])
        return valdict
    except:
        raise InvalidValueError("You didn't supply a number of steps") def wt_validator(omhe_value):
    valdict={}
    if omhe_value.endswith('l') or omhe_value.endswith('k'):
        valdict['wt_numeric']=omhe_value[:-1]
        valdict['wt_measure_unit']=omhe_value[-1]
    else:
        valdict['wt_numeric']=omhe_value
        valdict['wt_measure_unit']="l"
        
    try:
        f=float(valdict['wt_numeric'])
        if f < 0:
            error_msg="Weight may not be less than 0"
            raise InvalidValueError(error_msg)
        
    except ValueError:
        error_msg="I could not validate the value %s." % (valdict['wt_numeric'])
        raise InvalidMessageError(error_msg)
    
    return valdict def ffm_validator(omhe_value):
    valdict={}
    
    if omhe_value.isdigit():
        valdict['ffm_numeric']=omhe_value
        valdict['ffm_measure_unit']="l"
        try:
            x=float(valdict['ffm_numeric'])
            return valdict
        except:
            raise InvalidValueError(" You didn't supply a numerical free fat mass. ")
            
    if omhe_value.endswith('l'):
        valdict['ffm_numeric']=omhe_value[:-1]
        valdict['ffm_measure_unit']="l"
        try:
            x=float(valdict['ffm_numeric'])
            return valdict
        except:
            raise InvalidValueError(" You didn't supply a numerical free fat mass. ")
        
    
    if omhe_value.endswith('k'):
        valdict['ffm_numeric']=omhe_value[:-1]
        valdict['ffm_measure_unit']="k"
        try:
            x=float(valdict['ffm_numeric'])
            return valdict 
        except:
            raise InvalidValueError(" You didn't supply a numerical free fat mass. ")
    
    error_msg="I could not validate the value %s" % (omhe_value)
    raise InvalidMessageError(error_msg) def fm_validator(omhe_value):
    valdict={}
    if omhe_value.endswith('l') or omhe_value.endswith('k'):
        valdict['fm_numeric']=omhe_value[:-1]
        valdict['fm_measure_unit']=omhe_value[-1]
    else:
        valdict['fm_numeric']=omhe_value
        valdict['fm_measure_unit']="l"
        
    try:
        f=float(valdict['fm_numeric'])
        if f < 1.0:
            error_msg="Fat mass may not be less than 1."
            raise InvalidValueError(error_msg)
        
    except ValueError:
        error_msg="I could not validate the value %s is not a numerical fat mass. " % (valdict['fm_numeric'])
        raise InvalidMessageError(error_msg)

    return valdict def pbf_validator(omhe_value,DEFAULT_MIN_VALUE=1,DEFAULT_MAX_VALUE=95,DEFAULT_DEFAULT_VALUE=1,DEFAULT_BLANK_VALID=False,DEFAULT_STRING_VALID=False):
    """validate percent body fat"""
    valdict={}
    print omhe_value
    

    try:
        x=float(omhe_value,)
    except:
        raise InvalidValueError("You did not specify a number for percent body fat.")
    
    if  DEFAULT_MIN_VALUE <=  x <=  DEFAULT_MAX_VALUE:
        valdict['pbf_numeric']=omhe_value
        return valdict
    else:
        Error_Output = "The value supplied for percent body fat was outside the acceptable range. It must be between " + str(DEFAULT_MIN_VALUE) + " and " + str(DEFAULT_MAX_VALUE)
        if DEFAULT_BLANK_VALID == True:
            Error_Output = Error_Output + ", or a blank"
        if DEFAULT_STRING_VALID == True:
            Error_Output = Error_Output + ", or some text"

        Error_Output = Error_Output + "."

        raise InvalidValueError(Error_Output) def ci_validator(omhe_value):
    valdict={}
    if len(str(omhe_value))>=0 and len(str(omhe_value))<=120:
        valdict['ci_payload']=omhe_value
        return valdict
    else:
        raise InvalidValueError("Your message must be from 1-120 characters in length.") def pn_validator(omhe_value,DEFAULT_MIN_VALUE=0,DEFAULT_MAX_VALUE=10,DEFAULT_DEFAULT_VALUE=1,DEFAULT_BLANK_VALID=False,DEFAULT_STRING_VALID=True):
    """validate pain"""
    valdict={}
    
    if omhe_value.isdigit():
        valdict['pn_numeric']=omhe_value
    else:
        Error_Output = "You must supply a whole number between " + str(DEFAULT_MIN_VALUE) + " (best) and " + str(DEFAULT_MAX_VALUE) + " (worst) for pain level"
        if DEFAULT_BLANK_VALID == True:
            Error_Output = Error_Output + ", or a blank"
        if DEFAULT_STRING_VALID == True:
            Error_Output = Error_Output + ", or some text"
        Error_Output = Error_Output + "."

        raise InvalidValueError(Error_Output)

    try:
        x=float(valdict['pn_numeric'])
        if DEFAULT_MIN_VALUE <= x <= DEFAULT_MAX_VALUE:
            return valdict

        Error_Output = "You must supply a whole number between " + str(DEFAULT_MIN_VALUE) + " (best) and " + str(DEFAULT_MAX_VALUE) + " (worst) for pain level"
        if DEFAULT_BLANK_VALID == True:
            Error_Output = Error_Output + ", or a blank"
        if DEFAULT_STRING_VALID == True:
            Error_Output = Error_Output + ", or some text"
        Error_Output = Error_Output + "."

        raise InvalidValueError(Error_Output)
    except:
        Error_Output = "You must supply a whole number between " + str(DEFAULT_MIN_VALUE) + " (best) and " + str(DEFAULT_MAX_VALUE) + " (worst) for pain level"
        if DEFAULT_BLANK_VALID == True:
            Error_Output = Error_Output + ", or a blank"
        if DEFAULT_STRING_VALID == True:
            Error_Output = Error_Output + ", or some text"
        Error_Output = Error_Output + "."

        raise InvalidValueError(Error_Output) def md_validator(omhe_value,DEFAULT_MIN_VALUE=0,DEFAULT_MAX_VALUE=10,DEFAULT_DEFAULT_VALUE=1,DEFAULT_BLANK_VALID=False,DEFAULT_STRING_VALID=False):
    """validate mood"""
    valdict={}
    
    if omhe_value.isdigit():
        valdict['md_numeric']=omhe_value
    else:
        Error_Output = "You must supply a number between " + str(DEFAULT_MIN_VALUE) + " (worst) and " + str(DEFAULT_MAX_VALUE) + " (best) for mood"
        if DEFAULT_BLANK_VALID == True:
            Error_Output = Error_Output + ", or a blank"
        if DEFAULT_STRING_VALID == True:
            Error_Output = Error_Output + ", or some text"
        Error_Output = Error_Output + "."

        raise InvalidValueError(Error_Output)
    try:
        x=float(valdict['md_numeric'])
        if DEFAULT_MIN_VALUE <= x <= DEFAULT_MAX_VALUE:
            return valdict

        Error_Output = "You must supply a number between " + str(DEFAULT_MIN_VALUE) + " (worst) and " + str(DEFAULT_MAX_VALUE) + " (best) for mood"
        if DEFAULT_BLANK_VALID == True:
            Error_Output = Error_Output + ", or a blank"
        if DEFAULT_STRING_VALID == True:
            Error_Output = Error_Output + ", or some text"
        Error_Output = Error_Output + "."

        raise InvalidValueError(Error_Output)
    except:
        Error_Output = "You must supply a number between " + str(DEFAULT_MIN_VALUE) + " (worst) and " + str(DEFAULT_MAX_VALUE) + " (best) for mood"
        if DEFAULT_BLANK_VALID == True:
            Error_Output = Error_Output + ", or a blank"
        if DEFAULT_STRING_VALID == True:
            Error_Output = Error_Output + ", or some text"
        Error_Output = Error_Output + "."

        raise InvalidValueError(Error_Output) def frv_validator(omhe_value):
    valdict={}
    if omhe_value[0] == "=":
        omhe_value=omhe_value[1:]
        
    if omhe_value[-1].isdigit():
        valdict[omhe_value[:-1]]=str(omhe_value[-1])
        freggiename=omhe_value[:-1]
    else:
        valdict[omhe_value[:]]="1"
        freggiename=omhe_value[:]
    
    if freggies.__contains__(freggiename)==False:
        error_msg="%s is not a valid fruit or veggie." % (freggiename)
        raise InvalidMessageError(error_msg)

    return valdict def one_to_ten_or_blank_or_string_validator(omhe_value,DEFAULT_MIN_VALUE=0,DEFAULT_MAX_VALUE=10,DEFAULT_DEFAULT_VALUE=1,DEFAULT_BLANK_VALID=True,DEFAULT_STRING_VALID=True):
    """validate one to ten or blank or string"""
    valdict={}
    omhe_value=str(omhe_value)
    if omhe_value.isdigit():
        if (DEFAULT_MIN_VALUE <= int(omhe_value) <= DEFAULT_MAX_VALUE):
        # if (0 <= int(omhe_value) <= 10):
            valdict['one_to_ten_numeric']=omhe_value
        else:
            Error_Output = "You must supply a number between " + str(DEFAULT_MIN_VALUE) + " and " + str(DEFAULT_MAX_VALUE)
            if DEFAULT_BLANK_VALID == True:
                Error_Output = Error_Output + ", or a blank"
            if DEFAULT_STRING_VALID == True:
                Error_Output = Error_Output + ", or some text"
            Error_Output = Error_Output + "."
            raise InvalidValueError(Error_Output)
    elif omhe_value=="":
        valdict['one_to_ten_numeric']= str(DEFAULT_DEFAULT_VALUE)
    else:
        valdict['one_to_ten_numeric']= str(DEFAULT_DEFAULT_VALUE)
    
    return valdict def dummy_validator(omhe_value):
    valdict={}
    valdict['value']=omhe_value
    return valdict def one_to_onehundred_validator(omhe_value,DEFAULT_MIN_VALUE=0,DEFAULT_MAX_VALUE=100,DEFAULT_DEFAULT_VALUE=1,DEFAULT_BLANK_VALID=False,DEFAULT_STRING_VALID=False):
    """validate one to one hundred"""
    valdict={}
    omhe_value=str(omhe_value)
    if omhe_value.isdigit() and  (DEFAULT_MIN_VALUE <= int(omhe_value) <= DEFAULT_MAX_VALUE):
        valdict['one_to_ten_numeric']=omhe_value
    else:
        Error_Output = "You must supply a number between " + str(DEFAULT_MIN_VALUE) + " and " + str(DEFAULT_MAX_VALUE)
        if DEFAULT_BLANK_VALID == True:
            Error_Output = Error_Output + ", or a blank"
        if DEFAULT_STRING_VALID == True:
            Error_Output = Error_Output + ", or some text"
        Error_Output = Error_Output + "."

        raise InvalidValueError(Error_Output)
    
    return valdict def dt_helper_validator(helper_value):

    if helper_value.startswith("="):
        helper_value=helper_value[1:]
    
    try:
        time_struct = time.strptime(helper_value, "%Y%m%d:%H%M%Sz")
        mydate= datetime.fromtimestamp(time.mktime(time_struct))
    except:
        try:
            time_struct = time.strptime(helper_value, "%Y%m%d:%H%M%SZ")
            mydate= datetime.fromtimestamp(time.mktime(time_struct))
        except:
            try:
                time_struct = time.strptime(helper_value, "%Y%m%d:%H%M%S")
                mydate= datetime.fromtimestamp(time.mktime(time_struct))
            except:
                raise InvalidHelperFormatError, "The datetime was not formatted correctly."
    
    return { 'event_datetime': str(mydate)} def tz_helper_validator(helper_value):
    
    if helper_value.startswith("="):
        helper_value=omhe_value[1:]
    
    """ Validate timezone helper."""
    if type(helper_value).__name__!='str' and \
       type(helper_value).__name__!='unicode' and \
       type(helper_value).__name__!='int' and \
       type(helper_value).__name__!='float':
	    """Make sure the input is a string or unicode"""
	    raise InvalidMessageError, "The omhe_command was not a string"
    
    if helper_value.find(":")!=-1:
        orig_value=helper_value
        helper_value=helper_value.replace(":",".")
    try:
        val=float(helper_value)
    except:
        
        raise InvalidHelperFormatError, "TimeZoneOffset 'tz' is not an integer or float"
    
    if not (-12 <= val <=14 ):
        raise InvalidHelperFormatError, "TimeZoneOffset 'tz' mut be between -12 and +14"
    
    helper_value=helper_value.replace(".",":")
    
    return {'event_timezone':helper_value} def pts_helper_validator(omhe_value):
    """validate positive or negative integer"""

    print omhe_value
    if omhe_value.startswith("="):
        omhe_value=omhe_value[1:]
    valdict={}
    negative=False
    if omhe_value.isdigit() or omhe_value[1:].isdigit():
        valdict['points']=omhe_value
    else:
        raise InvalidValueError("You must supply a whole number")
    
    return valdict
import os, sys, re, uuid
 import simplejson as json
 import json
from datetime import datetime
from omhe.core.validators.validator_errors import *
from omhe.core.validators.bg_validator import bg_validator
from omhe.core.validators.bp_validator import bp_validator
from omhe.core.validators.sbp_validator import sbp_validator
from omhe.core.validators.st_validator import st_validator
from omhe.core.validators.wt_validator import wt_validator
from omhe.core.validators.ffm_validator import ffm_validator
from omhe.core.validators.fm_validator import fm_validator
from omhe.core.validators.pbf_validator import pbf_validator
from omhe.core.validators.ci_validator import ci_validator
from omhe.core.validators.pn_validator import pn_validator
from omhe.core.validators.md_validator import md_validator
from omhe.core.validators.frv_validator import frv_validator
from omhe.core.validators.one_to_ten_or_blank_or_string_validator import one_to_ten_or_blank_or_string_validator
from omhe.core.validators.dummy_validator import dummy_validator
from omhe.core.validators.one_to_onehundred_validator import one_to_onehundred_validator
from omhe.core.validators.dt_helper_validator import dt_helper_validator
from omhe.core.validators.tz_helper_validator import tz_helper_validator
from omhe.core.validators.pts_helper_validator import pts_helper_validator
#An OMHE Microsyntax parser class.
# Alan Viars, Videntity 2010


try:
except:



class parseomhe:
    """A class to parse omhe strings into  their respective sub parts."""
    command_tuple =          	None
    helper_tuple =           	None
    validator_dict =         	None
    helper_validator_dict =  	None
    omhe_dict =              	None
    event_timezone =            0
    transaction_timezone =      0

    
    def __init__(self,**kwargs):
        
        """This dict of tuples contains all possible omhe values and aliases"""
        self.command_dict={
            'bp': ('bloodpressure',),
	    'sbp': ('sendbloodpressure',),
	    'bg': ('bloodglucose',),
            'wt': ('weight',),
	    'fm': ('fatmass',),
	    'ffm': ('freefatmass',),
            'pbf': ('percentbodyfat',),
	    'st': ('steps','spd','fitbit'),
            'gbp': ('getbloodpressure',),
	    'ci': ('checkin', 'check-in','check',),
            'pn': ('pain',),
	    'md': ('mood',),
	    'frt': ('fruit',),
	    'veg': ('vegetable','veggie'),
	    'frv': ('freggie',),
	    'sch': ('starch',),
	    'jnk': ('junk','junkfood'),
	    'wtr': ('water', 'h2o', 'h20'),
	    'alc': ('alcohol','beer', 'wine', 'shot'),
	    'eat': ('ate', 'tweat'),
	    'gym': ('workout',),
	    'ptn': ('protien',),
	    'crb': ('starch','carb', 'carbohydrate'),
	    'dry': ('dairy',),
	    'drk': ('drink',),
	    'que': ('question',),
	    'ans': ('answer',),
	    'pts': ('points','gems'),
	    'zeo': ('sleepscore','zscore'),    
	    'hivcd4': ('cd4-count',), 
	    'hivvl': ('hiv-viral-load',),
	    #TODO: Add others here...    
        }
        
	# Add items here that have no value (e.g. a name/statement only)
	self.no_value_command_dict={
	    'yes': ('y','si','ok',),
	    'gbp': ('getbloodpressure',),
	}

        self.helper_tuple=('id', 'dt', 'tz', 'points', 'hid', 'pw', 'pi', 'tm',
			   'uu', '#')
        """This tuple contains helpers"""
    
	"""
	This is where we map the command and/or its aliases to a
	validation function.  Define each function in its own file and class
	(under the validators directory).
	"""

        self.validator_dict={
                   'bp': bp_validator,
		   'sbp': sbp_validator,

		   'bg': bg_validator,