# Path: texts/models.py
# class Subscriber(models.Model):
#     sms_number = models.CharField(max_length=20, unique=True)
#     date_created = models.DateTimeField(auto_now_add=True)
#     active = models.BooleanField(default=True)
#     date_renewed = models.DateTimeField(null=True, blank=True)
#     lifetime = models.BooleanField(default=False)
#     note = models.CharField(max_length=100, null=True, blank=True)
# 
#     @property
#     def expired(self):
#         if self.lifetime:
#             return False
#         date_renewed = self.date_renewed or self.date_created
#         # is their renewal date before expiration_days ago?
#         return date_renewed < timezone.now() - datetime.timedelta(days=settings.EXPIRATION_DAYS)
# 
#     def renew(self):
#         self.date_renewed = timezone.now()
#         self.active = True
# 
#     def __unicode__(self):
#         return self.sms_number
# 
# Path: util/showerthoughts.py
# def get_todays_thought():
#     thought = ShowerThought.objects.filter(date=datetime.datetime.today(), active=True).first()
#     if thought:
#         return thought
#     new_thought = get_thought()
#     showerthought = ShowerThought.objects.create(thought_text=new_thought.title,
#                                                  post_id=new_thought.id,
#                                                  url=new_thought.url,
#                                                  date=datetime.datetime.today(),
#                                                  active=True)
#     cache.set('todays_thought_text', new_thought.title)
#     # post a notification comment on the thread for this showerthought
#     bot = ShowerBot()
#     bot.login()
#     bot.post_notification(showerthought)
#     return showerthought
# 
# Path: util/texter.py
# class DuplicateTextException(Exception):
#     pass
# 
# class Texter(object):
#     def __init__(self):
#         self.client = TwilioRestClient(settings.TWILIO_SID, settings.TWILIO_TOKEN)
# 
#     def send_text(self, subscriber, message, post_id):
#         if TextSend.objects.filter(subscriber=subscriber, post_id=post_id).exists():
#             logging.warning('Attempted to send a duplicate text. Won\'t do it.')
#             raise DuplicateTextException()
#         try:
#             self.client.messages.create(
#                 to=subscriber.sms_number,
#                 from_=settings.TWILIO_NUMBER,
#                 body=message,
#             )
#         except TwilioRestException as e:
#             logging.error('Exception sending number to: ' + subscriber.sms_number + ' - ' + str(e))
#             TextSend.objects.create(
#                 subscriber=subscriber,
#                 post_id=post_id,
#                 message_text=message,
#                 sucess=False,
#                 result_message=str(e),
#             )
#             #TODO: refactor into a configurable list
#             if 'not a valid phone number' in str(e) or 'violates a blacklist rule' in str(e) or 'not a mobile number' in str(e):
#                 subscriber.active = False
#                 subscriber.save()
#             raise e
#         TextSend.objects.create(
#             subscriber=subscriber,
#             post_id=post_id,
#             message_text=message,
#         )
# 
#     def send_todays_texts(self):
#         ret = []
#         thought = get_todays_thought()
#         for subscriber in Subscriber.objects.filter(active=True):
#             row = {'to': subscriber, 'action': 'showertext'}
#             message = thought.thought_text
#             post_id = thought.post_id
#             if subscriber.expired:
#                 row['action'] = 'expiration'
#                 subscriber.active = False
#                 subscriber.save()
#                 message = 'HOUSE KEEPING! I\'m clearing out old numbers to make room for more. If you like these, ' \
#                           'please resubscribe for free! http://www.showertexts.com'
#                 post_id = 'EXP-' + str(datetime.date.today())
#             try:
#                 self.send_text(subscriber, message, post_id)
#                 row['result'] = 'Success'
#             except DuplicateTextException:
#                 row['result'] = 'Duplicate'
#             except TwilioRestException as ex:
#                 row['result'] = 'Exception: ' + str(ex)
#                 logging.error('Exception sending number to: ' + subscriber.sms_number + ' - ' + str(ex))
#             ret.append(row)
#         return ret


import logging
from texts.models import Subscriber
from twilio import TwilioRestException
from util.showerthoughts import get_todays_thought
from util.texter import DuplicateTextException, Texter


def subscribe(sms_number):
    if not sms_number:
        return 'You sent nothing yo.'
    sms_number = filter(str.isdigit, str(sms_number))

# Path: texts/models.py
# class Subscriber(models.Model):
#     sms_number = models.CharField(max_length=20, unique=True)
#     date_created = models.DateTimeField(auto_now_add=True)
#     active = models.BooleanField(default=True)
#     date_renewed = models.DateTimeField(null=True, blank=True)
#     lifetime = models.BooleanField(default=False)
#     note = models.CharField(max_length=100, null=True, blank=True)
# 
#     @property
#     def expired(self):
#         if self.lifetime:
#             return False
#         date_renewed = self.date_renewed or self.date_created
#         # is their renewal date before expiration_days ago?
#         return date_renewed < timezone.now() - datetime.timedelta(days=settings.EXPIRATION_DAYS)
# 
#     def renew(self):
#         self.date_renewed = timezone.now()
#         self.active = True
# 
#     def __unicode__(self):
#         return self.sms_number
# 
# Path: util/showerthoughts.py
# def get_todays_thought():
#     thought = ShowerThought.objects.filter(date=datetime.datetime.today(), active=True).first()
#     if thought:
#         return thought
#     new_thought = get_thought()
#     showerthought = ShowerThought.objects.create(thought_text=new_thought.title,
#                                                  post_id=new_thought.id,
#                                                  url=new_thought.url,
#                                                  date=datetime.datetime.today(),
#                                                  active=True)
#     cache.set('todays_thought_text', new_thought.title)
#     # post a notification comment on the thread for this showerthought
#     bot = ShowerBot()
#     bot.login()
#     bot.post_notification(showerthought)
#     return showerthought
# 
# Path: util/texter.py
# class DuplicateTextException(Exception):
#     pass
# 
# class Texter(object):
#     def __init__(self):
#         self.client = TwilioRestClient(settings.TWILIO_SID, settings.TWILIO_TOKEN)
# 
#     def send_text(self, subscriber, message, post_id):
#         if TextSend.objects.filter(subscriber=subscriber, post_id=post_id).exists():
#             logging.warning('Attempted to send a duplicate text. Won\'t do it.')
#             raise DuplicateTextException()
#         try:
#             self.client.messages.create(
#                 to=subscriber.sms_number,
#                 from_=settings.TWILIO_NUMBER,
#                 body=message,
#             )
#         except TwilioRestException as e:
#             logging.error('Exception sending number to: ' + subscriber.sms_number + ' - ' + str(e))
#             TextSend.objects.create(
#                 subscriber=subscriber,
#                 post_id=post_id,
#                 message_text=message,
#                 sucess=False,
#                 result_message=str(e),
#             )
#             #TODO: refactor into a configurable list
#             if 'not a valid phone number' in str(e) or 'violates a blacklist rule' in str(e) or 'not a mobile number' in str(e):
#                 subscriber.active = False
#                 subscriber.save()
#             raise e
#         TextSend.objects.create(
#             subscriber=subscriber,
#             post_id=post_id,
#             message_text=message,
#         )
# 
#     def send_todays_texts(self):
#         ret = []
#         thought = get_todays_thought()
#         for subscriber in Subscriber.objects.filter(active=True):
#             row = {'to': subscriber, 'action': 'showertext'}
#             message = thought.thought_text
#             post_id = thought.post_id
#             if subscriber.expired:
#                 row['action'] = 'expiration'
#                 subscriber.active = False
#                 subscriber.save()
#                 message = 'HOUSE KEEPING! I\'m clearing out old numbers to make room for more. If you like these, ' \
#                           'please resubscribe for free! http://www.showertexts.com'
#                 post_id = 'EXP-' + str(datetime.date.today())
#             try:
#                 self.send_text(subscriber, message, post_id)
#                 row['result'] = 'Success'
#             except DuplicateTextException:
#                 row['result'] = 'Duplicate'
#             except TwilioRestException as ex:
#                 row['result'] = 'Exception: ' + str(ex)
#                 logging.error('Exception sending number to: ' + subscriber.sms_number + ' - ' + str(ex))
#             ret.append(row)
#         return ret


# Path: util/subscription.py
import logging
from texts.models import Subscriber
from twilio import TwilioRestException
from util.showerthoughts import get_todays_thought
from util.texter import DuplicateTextException, Texter



def subscribe(sms_number):
    if not sms_number:
        return 'You sent nothing yo.'
    sms_number = filter(str.isdigit, str(sms_number))

    subscriber, created = Subscriber.objects.get_or_create(sms_number=sms_number)