import time

from quixote import get_publisher

from quixote.html import htmlescape

from wcs.qommon import _
from wcs.qommon.storage import StorableObject
from wcs.qommon import get_cfg, get_logger
from wcs.qommon import errors
from wcs.qommon import misc

from wcs.qommon import emails
from wcs.qommon.sms import SMS
from wcs.qommon.admin.emails import EmailsDirectory

class AnnounceSubscription(StorableObject):
    _names = 'announce-subscriptions'
    _indexes = ['user_id']

    user_id = None
    email = None
    sms = None
    enabled = True
    enabled_sms = False
    enabled_themes = None

    def remove(self, type=None):
        """ type (string) : email or sms """
        if type == "email":
            self.email = None
        elif type == "sms":
            self.sms = None
            self.enabled_sms = False
        if not type or (not self.sms and not self.email):
            self.remove_self()
        else:
            self.store()
        
    def get_user(self):
        if self.user_id:
            try:
                return get_publisher().user_class.get(self.user_id)
            except KeyError:
                return None
        return None
    user = property(get_user)


class Announce(StorableObject):
    _names = 'announces'

    title = None
    text = None

    hidden = False

    publication_time = None
    modification_time = None
    expiration_time = None
    sent_by_email_time = None
    sent_by_sms_time = None
    theme = None

    position = None

    def sort_by_position(cls, links):
        def cmp_position(x, y):
            if x.position == y.position:
                return 0
            if x.position is None:
                return 1
            if y.position is None:
                return -1
            return cmp(x.position, y.position)
        links.sort(cmp_position)
    sort_by_position = classmethod(sort_by_position)

    def get_atom_entry(self):
        from pyatom import pyatom
        entry = pyatom.Entry()
        entry.id = self.get_url()
        entry.title = self.title

        entry.content.attrs['type'] = 'html'
        entry.content.text = str('<p>' + htmlescape(
                    unicode(self.text, get_publisher().site_charset).encode('utf-8')) + '</p>')

        link = pyatom.Link(self.get_url())
        entry.links.append(link)

        if self.publication_time:
            entry.published = misc.format_time(self.publication_time,
                    '%(year)s-%(month)02d-%(day)02dT%(hour)02d:%(minute)02d:%(second)02dZ',
                    gmtime = True)

        if self.modification_time:
            entry.updated = misc.format_time(self.modification_time,
                    '%(year)s-%(month)02d-%(day)02dT%(hour)02d:%(minute)02d:%(second)02dZ',
                    gmtime = True)

        return entry

    def get_url(self):
        return '%s/announces/%s/' % (get_publisher().get_frontoffice_url(), self.id)

    def store(self):
        self.modification_time = time.gmtime()
        StorableObject.store(self)

    def email(self, job=None):
        self.sent_by_email_time = time.gmtime()
        StorableObject.store(self)

        data = {
            'title': self.title,
            'text': self.text
        }

        subscribers = AnnounceSubscription.select(lambda x: x.enabled)

        rcpts = []
        for l in subscribers:
            if self.theme:
                if l.enabled_themes is not None:
                    if self.theme not in l.enabled_themes:
                        continue
            if l.user and l.user.email:
                rcpts.append(l.user.email)
            elif l.email:
                rcpts.append(l.email)

        emails.custom_template_email('aq-announce', data, email_rcpt=rcpts, hide_recipients=True)

    def sms(self, job=None):
        self.sent_by_sms_time = time.gmtime()
        StorableObject.store(self)

        subscribers = AnnounceSubscription.select(lambda x: x.enabled_sms)

        rcpts = []
        for sub in subscribers:
            if self.theme:
                if sub.enabled_themes is not None:
                    if self.theme not in sub.enabled_themes:
                        continue
            if sub.sms:
                rcpts.append(sub.sms)

        sms_cfg = get_cfg('sms', {})
        sender = sms_cfg.get('sender', 'AuQuotidien')[:11]
        message = "%s: %s" % (self.title, self.text)
        mode = sms_cfg.get('mode', 'none')
        sms = SMS.get_sms_class(mode)
        try:
            sms.send(sender, rcpts, message[:160])
        except errors.SMSError, e:
            get_logger().error(e)

    def get_published_announces(cls):
        announces = cls.select(lambda x: not x.hidden)
        announces.sort(lambda x,y: cmp(x.publication_time or x.modification_time,
                    y.publication_time or y.modification_time))
        announces = [x for x in announces if x.publication_time < time.gmtime()
                     and (x.expiration_time is None or x.expiration_time > time.gmtime())]
        announces.reverse()
        return announces
    get_published_announces = classmethod(get_published_announces)


EmailsDirectory.register('aq-announce',
        N_('Publication of announce to subscriber'),
        N_('Available variables: title, text'),
        default_subject = N_('Announce: [title]'),
        default_body = N_("""\
[text]

-- 
This is an announce sent to you by your city, you can opt to not receive
those messages anymore on the city website.
"""))

