# Path: RandoAmisSecours/models.py
# class Outing(models.Model):
#     class Meta:
#         app_label = 'RandoAmisSecours'
#         ordering = ['beginning', 'ending', 'alert', 'name']
# 
#     user = models.ForeignKey(User)
# 
#     # Visible information
#     name = models.CharField(max_length=200)
#     description = models.TextField()
#     status = models.IntegerField(choices=OUTING_STATUS, default=DRAFT)
# 
#     # Time frame: (begin, end, alert)
#     beginning = models.DateTimeField()
#     ending = models.DateTimeField()
#     alert = models.DateTimeField()
# 
#     # Position on the map
#     latitude = models.FloatField()
#     longitude = models.FloatField()
# 
#     def __str__(self):
#         return "%s: %s" % (self.user.get_full_name(), self.name)
# 
#     def getPercents(self):
#         current_time = datetime.utcnow().replace(tzinfo=utc)
#         # now < begin < end < alert
#         if current_time < self.beginning:
#             return (0, 0, 0)
#         # begin < end < alert < now
#         elif self.alert < current_time:
#             return (0, 0, 100)
#         # begin < now < end < alert
#         elif current_time < self.ending:
#             return (((current_time - self.beginning).total_seconds()) / float((self.alert - self.beginning).total_seconds()) * 100, 0, 0)
#         # begin < end < now < alert
#         else:
#             assert(current_time < self.alert)
#             return (((self.ending - self.beginning).total_seconds()) / float((self.alert - self.beginning).total_seconds()) * 100,
#                     ((current_time - self.ending).total_seconds()) / float((self.alert - self.beginning).total_seconds()) * 100,
#                     0)
# 
#     def is_running(self):
#         """ Return True if beginning <= now < end """
#         now = datetime.utcnow().replace(tzinfo=utc)
#         return self.beginning <= now and now < self.ending
# 
#     def is_late(self):
#         """ Return True if end <= now < alert """
#         now = datetime.utcnow().replace(tzinfo=utc)
#         return self.ending <= now and now < self.alert
# 
#     def is_alerting(self):
#         """ Return True if alert <= now """
#         now = datetime.utcnow().replace(tzinfo=utc)
#         return self.alert <= now
# 
#     is_running.boolean = True
#     is_late.boolean = True
#     is_alerting.boolean = True
# 
# CONFIRMED = 1
# 
# DRAFT = 0
# 
# Path: RandoAmisSecours/utils.py
# class Localize(object):
#     def __init__(self, language, timezone):
#         self.language = language
#         self.timezone = timezone
# 
#     def __enter__(self):
#         if self.language:
#             translation.activate(self.language)
#         if self.timezone:
#             timezone.activate(pytz.timezone(self.timezone))
# 
#     def __exit__(self, type_name, value, traceback):
#         if self.timezone:
#             timezone.deactivate()
#         if self.language:
#             translation.deactivate()
# 
# def send_mail_help(user, subject, template_name, ctx):
#     body = loader.render_to_string(template_name, ctx)
#     logger.info("Sending email to '%s' ('%s')", user.get_full_name(),
#                 user.email, extra={'data': ctx})
#     send_mail(subject, body, settings.DEFAULT_FROM_EMAIL, [user.email])
# 
# def send_sms(user, template_name, ctx):
#     # Check that the provider is available
#     if not user.profile.provider or not user.profile.provider_data:
#         return
# 
#     logger.info("Sending SMS to '%s' ('%s')",
#                 user.get_full_name(), user.profile.provider,
#                 extra={'data': ctx})
#     msg = loader.render_to_string(template_name, ctx)
# 
#     # Create the provider object
#     try:
#         provider = providers.create(user.profile.provider,
#                                     json.loads(user.profile.provider_data))
#     except NotImplementedError:
#         logger.error("Unknown provider '%s'", user.profile.provider,
#                      exc_info=True,
#                      extra={'data': {'user': user.get_full_name(),
#                                      'provider': user.profile.provider}})
# 
#     try:
#         provider.send_message(msg)
#     except Exception:
#         logger.error("Unable to send SMS", exc_info=True,
#                      extra={'data': {'user': user.get_full_name(),
#                                      'provider': user.profile.provider}})


from django.core.management.base import BaseCommand, CommandError
from django.core.urlresolvers import reverse
from django.utils.timesince import timesince
from django.utils.timezone import datetime, utc
from django.utils.translation import ugettext_lazy as _
from RandoAmisSecours.models import Outing, CONFIRMED, DRAFT
from RandoAmisSecours.utils import Localize, send_mail_help, send_sms
import logging

class Command(BaseCommand):
    help = 'Alert the user or his friends that he is late'

    def add_arguments(self, parser):
        parser.add_argument('--interval', dest='interval', default=10,
                            type=int, help='Check interval in minutes')
        parser.add_argument('--alert', dest='alert', default=60,
                            type=int, help='Alerting interval')
        parser.add_argument('--url', dest='base_url',
                            help='Base URL of the website')

    def handle(self, *args, **kwargs):
        if kwargs.get('base_url', None) is None:
            raise CommandError('url option is required')

        logger.info("Running Alert script")
        now = datetime.utcnow().replace(tzinfo=utc)

        # Transform all DRAFT into CONFIRMED if the beginning is over
        logger.debug('Transforming DRAFTs')
        outings = Outing.objects.filter(status=DRAFT, beginning__lt=now)
        for outing in outings:
            logger.info("Confirm: '%s' (owner: '%s')", outing.name,
                        outing.user.get_full_name())
            outing.status = CONFIRMED
            outing.save()

        # Grab all late outings
        logger.debug('Alerting owner and friends')

# Path: RandoAmisSecours/models.py
# class Outing(models.Model):
#     class Meta:
#         app_label = 'RandoAmisSecours'
#         ordering = ['beginning', 'ending', 'alert', 'name']
# 
#     user = models.ForeignKey(User)
# 
#     # Visible information
#     name = models.CharField(max_length=200)
#     description = models.TextField()
#     status = models.IntegerField(choices=OUTING_STATUS, default=DRAFT)
# 
#     # Time frame: (begin, end, alert)
#     beginning = models.DateTimeField()
#     ending = models.DateTimeField()
#     alert = models.DateTimeField()
# 
#     # Position on the map
#     latitude = models.FloatField()
#     longitude = models.FloatField()
# 
#     def __str__(self):
#         return "%s: %s" % (self.user.get_full_name(), self.name)
# 
#     def getPercents(self):
#         current_time = datetime.utcnow().replace(tzinfo=utc)
#         # now < begin < end < alert
#         if current_time < self.beginning:
#             return (0, 0, 0)
#         # begin < end < alert < now
#         elif self.alert < current_time:
#             return (0, 0, 100)
#         # begin < now < end < alert
#         elif current_time < self.ending:
#             return (((current_time - self.beginning).total_seconds()) / float((self.alert - self.beginning).total_seconds()) * 100, 0, 0)
#         # begin < end < now < alert
#         else:
#             assert(current_time < self.alert)
#             return (((self.ending - self.beginning).total_seconds()) / float((self.alert - self.beginning).total_seconds()) * 100,
#                     ((current_time - self.ending).total_seconds()) / float((self.alert - self.beginning).total_seconds()) * 100,
#                     0)
# 
#     def is_running(self):
#         """ Return True if beginning <= now < end """
#         now = datetime.utcnow().replace(tzinfo=utc)
#         return self.beginning <= now and now < self.ending
# 
#     def is_late(self):
#         """ Return True if end <= now < alert """
#         now = datetime.utcnow().replace(tzinfo=utc)
#         return self.ending <= now and now < self.alert
# 
#     def is_alerting(self):
#         """ Return True if alert <= now """
#         now = datetime.utcnow().replace(tzinfo=utc)
#         return self.alert <= now
# 
#     is_running.boolean = True
#     is_late.boolean = True
#     is_alerting.boolean = True
# 
# CONFIRMED = 1
# 
# DRAFT = 0
# 
# Path: RandoAmisSecours/utils.py
# class Localize(object):
#     def __init__(self, language, timezone):
#         self.language = language
#         self.timezone = timezone
# 
#     def __enter__(self):
#         if self.language:
#             translation.activate(self.language)
#         if self.timezone:
#             timezone.activate(pytz.timezone(self.timezone))
# 
#     def __exit__(self, type_name, value, traceback):
#         if self.timezone:
#             timezone.deactivate()
#         if self.language:
#             translation.deactivate()
# 
# def send_mail_help(user, subject, template_name, ctx):
#     body = loader.render_to_string(template_name, ctx)
#     logger.info("Sending email to '%s' ('%s')", user.get_full_name(),
#                 user.email, extra={'data': ctx})
#     send_mail(subject, body, settings.DEFAULT_FROM_EMAIL, [user.email])
# 
# def send_sms(user, template_name, ctx):
#     # Check that the provider is available
#     if not user.profile.provider or not user.profile.provider_data:
#         return
# 
#     logger.info("Sending SMS to '%s' ('%s')",
#                 user.get_full_name(), user.profile.provider,
#                 extra={'data': ctx})
#     msg = loader.render_to_string(template_name, ctx)
# 
#     # Create the provider object
#     try:
#         provider = providers.create(user.profile.provider,
#                                     json.loads(user.profile.provider_data))
#     except NotImplementedError:
#         logger.error("Unknown provider '%s'", user.profile.provider,
#                      exc_info=True,
#                      extra={'data': {'user': user.get_full_name(),
#                                      'provider': user.profile.provider}})
# 
#     try:
#         provider.send_message(msg)
#     except Exception:
#         logger.error("Unable to send SMS", exc_info=True,
#                      extra={'data': {'user': user.get_full_name(),
#                                      'provider': user.profile.provider}})


# Path: RandoAmisSecours/management/commands/alert.py
from django.core.management.base import BaseCommand, CommandError
from django.core.urlresolvers import reverse
from django.utils.timesince import timesince
from django.utils.timezone import datetime, utc
from django.utils.translation import ugettext_lazy as _
from RandoAmisSecours.models import Outing, CONFIRMED, DRAFT
from RandoAmisSecours.utils import Localize, send_mail_help, send_sms
import logging


class Command(BaseCommand):
    help = 'Alert the user or his friends that he is late'

    def add_arguments(self, parser):
        parser.add_argument('--interval', dest='interval', default=10,
                            type=int, help='Check interval in minutes')
        parser.add_argument('--alert', dest='alert', default=60,
                            type=int, help='Alerting interval')
        parser.add_argument('--url', dest='base_url',
                            help='Base URL of the website')

    def handle(self, *args, **kwargs):
        if kwargs.get('base_url', None) is None:
            raise CommandError('url option is required')

        logger.info("Running Alert script")
        now = datetime.utcnow().replace(tzinfo=utc)

        # Transform all DRAFT into CONFIRMED if the beginning is over
        logger.debug('Transforming DRAFTs')
        outings = Outing.objects.filter(status=DRAFT, beginning__lt=now)
        for outing in outings:
            logger.info("Confirm: '%s' (owner: '%s')", outing.name,
                        outing.user.get_full_name())
            outing.status = CONFIRMED
            outing.save()

        # Grab all late outings
        logger.debug('Alerting owner and friends')

        outings = Outing.objects.filter(status=CONFIRMED, ending__lt=now)