#!/usr/bin/env python

#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

# FunnyordieScreenlet (c) spdf (aka Mark Hayes) 2008 <mcleodm@gmail.com>

# INFO:
# - Displays the 20 most recent additions to Funnyordie.com
# - Scrapes site with regex, will break if they change things
# 
# TODO: 
# - Figure out why click events are sometimes counted twice
# - Possibly expand to include other sections from website
# - Ugly.

import screenlets
from screenlets.options import StringOption 
import gobject
import cairo
import os, re, urllib, urllib2
import gtk
import pango

# FoD Sites
RECENT_URL = 'http://www.funnyordie.com/browse/videos/all/all/most_recent'
VID_URL = 'http://www2.funnyordie.com/'
VID_PAGE = 'http://www.funnyordie.com/videos/'
TEMP_DIR = '/tmp/'
#use gettext for translation
import gettext

_ = screenlets.utils.get_translator(__file__)

def tdoc(obj):
	obj.__doc__ = _(obj.__doc__)
	return obj

@tdoc
class FunnyordieScreenlet (screenlets.Screenlet):
   """Shows 20 most recent video posts on FunnyOrDie.com"""
   __name__ = 'FunnyordieScreenlet'
   __version__ = '0.1.2'
   __author__ = 'spdf'
   __desc__ = __doc__

   # internals
   __timeout = None 
   update_interval = 120 # seconds
   current_vid = 0
   haveVids = False
   tempTitles = []
   tempCodes = []
   tempRatings = []
   tempDurations = []
   font = 'Purisa'
   player_path = '' 

   def __init__ (self, **keyword_args):
      # Create screenlet
      screenlets.Screenlet.__init__(self, width=500, height=168, uses_theme=True, **keyword_args)
      self.theme_name = "default" 
      self.update_interval = self.update_interval
      
      # Add launch options
      self.add_options_group(_('Launching'), _('Application for launching'))
      self.add_option(StringOption(_('Launching'),'player_path',self.player_path,_('Video player path'),_('Leave blank to launch web browser')))

      # get vids
      self.check_for_new_vid()
      
   def on_draw (self, ctx):
      ctx.scale(self.scale, self.scale)
      ctx.set_operator(cairo.OPERATOR_OVER)
      if (self.theme):
         ctx.set_source_rgb(0.8,0.8,0.8)
         self.theme.draw_rectangle(ctx,0,0,self.width,self.height,fill=True)
         if (self.haveVids):
            # load thumbnail into pixbuf
            imgFilename = TEMP_DIR + self.tempCodes[self.current_vid] + ".jpg"
            pixbuf = gtk.gdk.pixbuf_new_from_file(imgFilename)

            # draw background 
            ctx.set_source_rgb(0.0,0.0,0.0)
            self.theme.draw_rectangle(ctx,6,6,self.width-12,self.height-12,fill=True)
 
            # draw logo
            ctx.save()
            ctx.translate(195,20)
            self.theme.render(ctx, 'logo')
            ctx.restore()

            # draw thubnail
            ctx.set_source_pixbuf(pixbuf,20,20)
            ctx.paint()
            
            # draw navigation
            ctx.save()
            ctx.translate(10,110)
            if (self.current_vid < 19):
               self.theme.render(ctx, 'go-previous')
            ctx.translate(92,0)
            if (self.current_vid > 0):
               self.theme.render(ctx, 'go-next')
            ctx.restore() 

            # draw text
            ctx.save()
            ctx.set_source_rgb(1,1,1)
            self.theme.draw_text(ctx, self.tempVids[self.current_vid] + " " + self.tempDurations[self.current_vid], 150, 66, self.font, 12, self.width - 170, pango.ALIGN_CENTER)
            self.theme.draw_text(ctx, self.tempRatings[self.current_vid], 150, 120, self.font, 8, self.width - 170, pango.ALIGN_CENTER)
            self.theme.draw_text(ctx, str(self.current_vid + 1),48,115, self.font, 20, 64, pango.ALIGN_CENTER)
            ctx.restore()

   def on_draw_shape (self, ctx):
      self.on_draw(ctx)

   def update (self):
      gobject.idle_add(self.check_for_new_vid)
      self.redraw_canvas() 
      return True
 
   def check_for_new_vid (self):
      try:
         getVids = PageParser()
         getVids.load(RECENT_URL)

         for each in range(0, len(getVids.videoUrls)):
            imgFilename = TEMP_DIR + getVids.videoUrls[each] + ".jpg"
            if (os.path.exists(imgFilename) == False):
               if (urllib.urlretrieve(getVids.videoImages[each], imgFilename)):
                  self.current_vid = 0
         self.tempVids = getVids.videoTitles
         self.tempCodes = getVids.videoUrls
         self.tempRatings = getVids.videoRatings
         self.tempDurations = getVids.videoDurations
         self.haveVids = True
      except:
         self.haveVids = False      

   def on_init (self):
     self.add_default_menuitems()

   def on_mouse_down(self, event):
      if (event.button != 1):
         return False

      if ((event.y > (120 * self.scale)) and (event.y < (168 * self.scale))):
         if ((event.x > (20 * self.scale)) and (event.x < (68 * self.scale))):
            self.current_vid = self.current_vid + 1
            if (self.current_vid > 19):
               self.current_vid = 19
         if ((event.x > (102 * self.scale)) and (event.x < (150 * self.scale))): 
            self.current_vid = self.current_vid - 1
            if (self.current_vid < 0):
               self.current_vid = 0
      if ((event.y > (20 * self.scale)) and (event.y < (110 * self.scale)) and (event.x > (20 * self.scale)) and (event.x < (140 * self.scale))):
         if (self.player_path):
             cmd = self.player_path + " " + VID_URL + self.tempCodes[self.current_vid] + ".flv"
         else:
             cmd = "xdg-open " + VID_PAGE + self.tempCodes[self.current_vid]
         os.system(cmd + "&")

   def __setattr__ (self, name, value):
      screenlets.Screenlet.__setattr__ (self, name, value)
      if name == "update_interval":
         if value > 0:
            self.__dict__['update_interval'] = value
            if self.__timeout:
               gobject.source_remove(self.__timeout)
            self.__timeout = gobject.timeout_add(value * 1000, self.update)
         else:
            pass

class PageParser(object):
  def __init__(self):
    self.videoTitles = []
    self.videoUrls = []
    self.videoImages = []
    self.videoRatings = []
    self.videoDurations = []

  def load(self, pageUrl):
    # retrieve page
    urllib.urlcleanup()
    videoPage = urllib.urlopen(pageUrl)
    videoHtml = videoPage.read()

    # get info
    self.videoUrls = re.compile('<div class="vp detailed_vp "><div class="thumb "><a href="/videos/(..........)">',re.IGNORECASE).findall(videoHtml)
    self.videoImages = re.compile('height="90" src="(.*?)"',re.IGNORECASE).findall(videoHtml)
    self.videoTitles = re.compile('<img alt="(.*?) from .*" height',re.IGNORECASE).findall(videoHtml)
    self.videoRatings = re.compile('details\'><a href="/browse/videos/all/.*?" rel="nofollow" title="(.*?)"').findall(videoHtml)
    self.videoDurations = re.compile('\'duration\'>(\(.*?\))').findall(videoHtml) 

if __name__ == "__main__":
   #Create screenlet session
   import screenlets.session
   screenlets.session.create_session(FunnyordieScreenlet)
