# Path: sendinel/backend/models.py
# class Patient(User):
#     """
#     Represent a patient.
#     """
#     
#     phone_number = models.CharField(max_length = 20)
#     
#     def __unicode__(self):
#         return "Patient <%s>" % self.phone_number
# 
# class WayOfCommunication(models.Model):
#     """
#     Represent a possible Way of Communication like SMS
#     """
#     
#     name = models.CharField(max_length = 255, blank = False, null = False)
#     verbose_name = models.CharField(max_length = 255)
#     enabled = models.BooleanField()
#     can_send_immediately = models.BooleanField()
#     
#     def __unicode__(self):
#         return self.verbose_name
# 
# Path: sendinel/infoservices/models.py
# class InfoMessage(Sendable):
#     """
#     Define a InfoMessage.
#     """
# 
#     template = Template("$text")
#     text = models.TextField()
#     
#     def __unicode__(self):
#         return "InfoMessage to %s: '%s' via %s" % \
#                                         (self.recipient.phone_number,
#                                          self.text,
#                                          self.way_of_communication)
#     
#     def get_data_for_sms(self):
#         """
#         Prepare OutputData for sms.
#         Generate the message for an InfoMessage.
#         Return SMSOutputData for sending.
#         """
#         
#         data = SMSOutputData()           
#         data.data = texthelper.generate_text({'text': self.text},
#                                              InfoMessage.template)
#         data.phone_number = self.recipient.phone_number
#                 
#         return data
#         
#     def get_data_for_voice(self):
#         """
#         Prepare OutputData for voicecall.
#         Generate the message for an InfoMessage.
#         Return VoiceOutputData for sending.
#         """
#         
#         data = VoiceOutputData()
#         data.data = self.text
#         data.phone_number = self.recipient.phone_number
#             
#         return data
# 
# class InfoService(models.Model):
#     """
#     Represent a user group.
#     Existing types are 'information' and 'medicine' 
#     whereas information-groups send regular messages to their 
#     subscribers, medicine deletes the group after sending a message
#     """
#     
#     TYPES = (
#         ('information', ugettext_lazy("Information Group")),
#         ('medicine', ugettext_lazy('Waiting List for Medicine'))
#     )
#     TYPE_TEXTS = {
#         'information': {
#             'title': ugettext_lazy('Information Groups'),
#             'name': ugettext_lazy('information group'),
#             'members_button': ugettext_lazy('Group members'),
#             'remove_button': ugettext_lazy('Remove group'),
#             'remove_patient_button': ugettext_lazy('Remove patient from group'),
#             'form_field_description': ugettext_lazy('Inform patients about:'),
#             'table_head': ugettext_lazy('Information')
#         },
#         'medicine': {
#             'title': ugettext_lazy('Waiting Lists for Medicine'),
#             'name': ugettext_lazy('waiting list for medicine'),
#             'members_button': ugettext_lazy('List members'),
#             'remove_button': ugettext_lazy('Remove list'),
#             'remove_patient_button': ugettext_lazy('Remove patient from list'),
#             'form_field_description':
#             ugettext_lazy('The patients are waiting for the following medicine:'),
#             'table_head': ugettext_lazy('Medicine')
#         },
#     }
#     
#     
#     members = models.ManyToManyField(Patient, through = "Subscription")
#     name = models.CharField(max_length = 255,
#                             default = None,
#                             unique = True,
#                             blank = False,
#                             null = False,
#                             verbose_name = ugettext_lazy("name"))
#     type = models.CharField(max_length = 255, 
#                             choices = TYPES,
#                             default = None,
#                             blank = False, 
#                             null = False)
#     
#     class Meta:
#         verbose_name = ugettext_lazy("Information service")
#                             
#     def __unicode__(self):
#         return self.name
#     
#     def member_count(self):
#         return self.members.all().count()
#     
#     def texts(self):
#         """
#         Returns the text blocks associated with the group's type.
#         """
#         return self.TYPE_TEXTS[self.type]
# 
# class Subscription(models.Model):
#     """
#     Represents a patient's subscription to an infoservice
#     """
# 
#     patient = models.ForeignKey(Patient)
#     infoservice = models.ForeignKey(InfoService)
# 
#     way_of_communication = models.ForeignKey(WayOfCommunication)
# 
#     def __unicode__(self):
#         return "%s %s" % (unicode(self.infoservice), \
#                           unicode(self.patient.phone_number))
# 
# Path: sendinel/logger.py
# LOG_MSG_FORMAT = '%(asctime)s %(levelname)s %(filename)s#%(lineno)d %(message)s'
# def log_request(viewfunc):
#     def do_log_request(*args, **kwargs):


from datetime import datetime
from sendinel.backend.models import Patient, \
                                    WayOfCommunication
from sendinel.infoservices.models import InfoMessage, \
                                         InfoService, \
                                         Subscription
from sendinel.logger import logger



def subscription_save(request, id):
    '''
        save patient and subscription
        @return subscription
    '''
    patient = request.session['patient']
    patient.save()
    way_of_communication = request.session['way_of_communication']
    infoservice = InfoService.objects.filter(pk = id)[0]
    subscription = Subscription(patient = patient,
                                way_of_communication = way_of_communication,
                                infoservice = infoservice)
    subscription.save()
    logger.info("Saved subscription %s of type %s.", 
                (unicode(subscription), 
                 unicode(subscription.infoservice.type)))
    return subscription
    
def create_messages_for_infoservice(infoservice, text):
    '''
        Put together all information for an infomessage and
        calls InfoService.create_scheduled_event
    '''
    
    for patient in infoservice.members.all():
        info_message = InfoMessage()
        info_message.text = text

# Path: sendinel/backend/models.py
# class Patient(User):
#     """
#     Represent a patient.
#     """
#     
#     phone_number = models.CharField(max_length = 20)
#     
#     def __unicode__(self):
#         return "Patient <%s>" % self.phone_number
# 
# class WayOfCommunication(models.Model):
#     """
#     Represent a possible Way of Communication like SMS
#     """
#     
#     name = models.CharField(max_length = 255, blank = False, null = False)
#     verbose_name = models.CharField(max_length = 255)
#     enabled = models.BooleanField()
#     can_send_immediately = models.BooleanField()
#     
#     def __unicode__(self):
#         return self.verbose_name
# 
# Path: sendinel/infoservices/models.py
# class InfoMessage(Sendable):
#     """
#     Define a InfoMessage.
#     """
# 
#     template = Template("$text")
#     text = models.TextField()
#     
#     def __unicode__(self):
#         return "InfoMessage to %s: '%s' via %s" % \
#                                         (self.recipient.phone_number,
#                                          self.text,
#                                          self.way_of_communication)
#     
#     def get_data_for_sms(self):
#         """
#         Prepare OutputData for sms.
#         Generate the message for an InfoMessage.
#         Return SMSOutputData for sending.
#         """
#         
#         data = SMSOutputData()           
#         data.data = texthelper.generate_text({'text': self.text},
#                                              InfoMessage.template)
#         data.phone_number = self.recipient.phone_number
#                 
#         return data
#         
#     def get_data_for_voice(self):
#         """
#         Prepare OutputData for voicecall.
#         Generate the message for an InfoMessage.
#         Return VoiceOutputData for sending.
#         """
#         
#         data = VoiceOutputData()
#         data.data = self.text
#         data.phone_number = self.recipient.phone_number
#             
#         return data
# 
# class InfoService(models.Model):
#     """
#     Represent a user group.
#     Existing types are 'information' and 'medicine' 
#     whereas information-groups send regular messages to their 
#     subscribers, medicine deletes the group after sending a message
#     """
#     
#     TYPES = (
#         ('information', ugettext_lazy("Information Group")),
#         ('medicine', ugettext_lazy('Waiting List for Medicine'))
#     )
#     TYPE_TEXTS = {
#         'information': {
#             'title': ugettext_lazy('Information Groups'),
#             'name': ugettext_lazy('information group'),
#             'members_button': ugettext_lazy('Group members'),
#             'remove_button': ugettext_lazy('Remove group'),
#             'remove_patient_button': ugettext_lazy('Remove patient from group'),
#             'form_field_description': ugettext_lazy('Inform patients about:'),
#             'table_head': ugettext_lazy('Information')
#         },
#         'medicine': {
#             'title': ugettext_lazy('Waiting Lists for Medicine'),
#             'name': ugettext_lazy('waiting list for medicine'),
#             'members_button': ugettext_lazy('List members'),
#             'remove_button': ugettext_lazy('Remove list'),
#             'remove_patient_button': ugettext_lazy('Remove patient from list'),
#             'form_field_description':
#             ugettext_lazy('The patients are waiting for the following medicine:'),
#             'table_head': ugettext_lazy('Medicine')
#         },
#     }
#     
#     
#     members = models.ManyToManyField(Patient, through = "Subscription")
#     name = models.CharField(max_length = 255,
#                             default = None,
#                             unique = True,
#                             blank = False,
#                             null = False,
#                             verbose_name = ugettext_lazy("name"))
#     type = models.CharField(max_length = 255, 
#                             choices = TYPES,
#                             default = None,
#                             blank = False, 
#                             null = False)
#     
#     class Meta:
#         verbose_name = ugettext_lazy("Information service")
#                             
#     def __unicode__(self):
#         return self.name
#     
#     def member_count(self):
#         return self.members.all().count()
#     
#     def texts(self):
#         """
#         Returns the text blocks associated with the group's type.
#         """
#         return self.TYPE_TEXTS[self.type]
# 
# class Subscription(models.Model):
#     """
#     Represents a patient's subscription to an infoservice
#     """
# 
#     patient = models.ForeignKey(Patient)
#     infoservice = models.ForeignKey(InfoService)
# 
#     way_of_communication = models.ForeignKey(WayOfCommunication)
# 
#     def __unicode__(self):
#         return "%s %s" % (unicode(self.infoservice), \
#                           unicode(self.patient.phone_number))
# 
# Path: sendinel/logger.py
# LOG_MSG_FORMAT = '%(asctime)s %(levelname)s %(filename)s#%(lineno)d %(message)s'
# def log_request(viewfunc):
#     def do_log_request(*args, **kwargs):


# Path: sendinel/infoservices/utils.py
from datetime import datetime
from sendinel.backend.models import Patient, \
                                    WayOfCommunication
from sendinel.infoservices.models import InfoMessage, \
                                         InfoService, \
                                         Subscription
from sendinel.logger import logger




def subscription_save(request, id):
    '''
        save patient and subscription
        @return subscription
    '''
    patient = request.session['patient']
    patient.save()
    way_of_communication = request.session['way_of_communication']
    infoservice = InfoService.objects.filter(pk = id)[0]
    subscription = Subscription(patient = patient,
                                way_of_communication = way_of_communication,
                                infoservice = infoservice)
    subscription.save()
    logger.info("Saved subscription %s of type %s.", 
                (unicode(subscription), 
                 unicode(subscription.infoservice.type)))
    return subscription
    
def create_messages_for_infoservice(infoservice, text):
    '''
        Put together all information for an infomessage and
        calls InfoService.create_scheduled_event
    '''
    
    for patient in infoservice.members.all():
        info_message = InfoMessage()
        info_message.text = text

        subscription = Subscription.objects.filter(patient = patient,