import datetime
import re

from linkeyes import wordpresslib
from linkeyes import feedparser
from linkeyes.pydelicious import DeliciousAPI
from string import Template

s = Template('<a href="$href">$description</a>')

VIDEOS = ['vimeo', 'youtube', 'qik']

VIDEO_RE = re.compile(r'.*%s.*' % ('|\['.join(VIDEOS)))

def get_yesterday():
    now = datetime.datetime.now()
    yesterday = now - datetime.timedelta(1)
    yesterday_str = yesterday.strftime('%Y-%m-%d')
    yesterday_str = '2009-03-23' #yesterday.strftime('%Y-%m-%d')
    return yesterday_str

def get_suffix(day):
    mod_num = day % 10
    if (mod_num == 1 and day != 11) :
        suffix ="st"
    elif (mod_num == 2 and day != 12):
        suffix = "nd"
    elif (mod_num == 3 and day != 13):
        suffix = "rd"
    else:
        suffix = "th"
    return suffix
  
def get_title():
    now = datetime.datetime.now()
    title = '%d%s %s' % (now.day, get_suffix(now.day), now.strftime('%B %Y'))
    return title

def get_link(href, link_string):
    return s.substitute(href=href, description=link_string)

def get_linkeyes(post):
    href = post['href']
    notes = post['extended']
    if notes:
        text = notes
    else:
        text = post['description']

    import re
    link_re = re.compile('.*(__(.*)__).*', re.MULTILINE|re.DOTALL)
    match = link_re.match(text)
    if match:
        groups = match.groups()
        link = get_link(href, groups[1])
        entry = text.replace(groups[0], link)
    else:
        entry = get_link(href, text)
    entry = "<li>%s</li>" % (entry)
    return entry

def postlinks(config):
    blog = config['blog']
    delicious = config['delicious']
    wp = wordpresslib.WordPressClient(blog['endpoint'], blog['username'], blog['password'])
    a = DeliciousAPI(delicious['username'], delicious['password'])

    posts = a.posts_get(tag=config['tag'], dt=get_yesterday())
    bits = []
    videos = []
    alltags = []
    for post in posts['posts']:
        tags = post['tag'].split()
        alltags.extend(tags)
        entry = get_linkeyes(post)
        if VIDEO_RE.match(entry):
            videos.append(entry)
        else:
            bits.append(entry)

    if 'publish_tags' in config:
        for tag in config['publish_tags'].split():
            alltags.append(tag)
        
    alltags = list(set(alltags))
    if bits or videos:
        alltags.remove(config['tag'])
        blogpost = '<ul class="linkeyes">%s%s</ul>' % (''.join(bits), ''.join(videos))
        print("Blogpost is %s" % (blogpost))
    
        p = wordpresslib.WordPressPost()
        p.title = '%s %s' % (config['title'], get_title())
        p.description = blogpost
        p.mt_keywords = alltags
        idNewPost = wp.newPost(p, True)
