import urllib
import hashlib
import re
import markdown
from datetime import datetime
from google.appengine.api import users

from models import *


__all__ = ['leave_room', 'gravatar', 'slugify', 'get_account', 'transform_message']


def leave_room(room=None, account=None, session=None):
    """
    Handles app logic for a user leaving a room.

    Must be passed *either* a Room and Account object, or a RoomList object.

    Examples
    --------
    leave_room(room=room_obj, account=account_obj)
    leave_room(session=roomlist_obj)
    """
    if room is not None and account is not None:
        session = RoomList.all().filter('room =', room).filter('account =', account).get()
    elif session is not None:
        room = session.room
        account = session.account
    else:
        raise TypeError("must specify either room and account, or session")

    # clean up the session record
    session.delete()

    # send a message to the room about the part
    timestamp = datetime.now()
    message = Message(sender=account, room=room, timestamp=timestamp,
                      event=Message_event_codes['part'])
    message.put()


def gravatar(email):
    size=30
    rating='g'
    default_image='identicon'
    gravatar_url = "http://www.gravatar.com/avatar.php?"
    #gravatar_url += hashlib.md5(email).hexdigest()
    gravatar_url += urllib.urlencode({
        'gravatar_id':hashlib.md5(email).hexdigest(),
        's':str(size),
        'r':rating,
        'd':default_image})
    return """<img src="%s" alt="gravatar" />""" % gravatar_url


def slugify(title):
    slug = title.lower()
    slug = re.sub(r'[^\w\s-]', '', slug)
    slug = re.sub(r'[\s_-]+', '-', slug)
    return slug


def get_account():
    user = users.get_current_user()
    account = Account.all().filter('user =', user).get()
    return account
    
def transform_message(message):
    content = message.content
    markdown.HTML_REMOVED_TEXT = ""
    md = markdown.Markdown(
            safe_mode="escape",
            output_format='html4'
    )
    md_nohtml = markdown.Markdown(
            safe_mode="replace",
            output_format='html4'
    )
    if content is not None:
        r="((?:https?)://[^ \t\n\r()\"']+)"
        m = re.search(r, content)
        if (m):
            url = m.group(1)
            r2="(?i)\.(jpg|png|gif)$"
            m = re.search(r2,url)
            new_content = ''
            if (m):
                new_content = '[![Image](' + url + ')](' + url +')'
            else:
                new_content = '<' + url + '>'
            content = re.sub(r,new_content,content)
        if (Message_event_names[message.event] == "topic"):
            message.content = md_nohtml.convert(content)
            message.content = re.sub("<\/?p>","", message.content)
        else:
            message.content = md.convert(content)
    else:
        message.content = ''
    return message

@@ -2181,18 +2181,34 @@
         
+content = re.sub(
 r
-=
 %22((?:htt
@@ -2236,384 +2236,109 @@
 %5D+)%22
-%0A        m = re.search(r, content)%0A        if (m):%0A            url = m.group(1)%0A            r2=%22(?i)%5C.(jpg%7Cpng%7Cgif)$%22%0A            m = re.search(r2,url)%0A            new_content = ''%0A            if (m):%0A                new_content = '%5B!%5BImage%5D(' + url + ')%5D(' + url +')'%0A            else:%0A                new_content = '%3C' + url + '%3E'%0A            content = re.sub(r,new_content,
+, r%22%3C%5C1%3E%22, content)%0A        content = re.sub(r%22%3C(http%5B%5E%3E%5D+(?:jpg%7Cpng%7Cgif))%3E%22, r%22%5B!%5BImage%5D(%5C1)%5D(%5C1)%22, 
 cont

handle linkifying multiple links.