'''
SVPlayer player backend objects

(c) 2011-2012 Jan ONDREJ (SAL) <ondrejj(at)salstar.sk>     

 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 2 of the License, or
 (at your option) any later version.
'''

import sys, os, time, glob
from urllib import pathname2url
#from config import *
from sgtk import *
from base import BasePlayerWidget

### Image player ###

class ImagePlayerWidget(BasePlayerWidget, Gtk.DrawingArea):
  name = 'image'
  def __init__(self, media=None, options=[]):
      Gtk.DrawingArea.__init__(self)
      self.timer = None
      self.paused = True
      self.size = (400, 300)
      self.pixbuf = None
      self.modify_bg(Gtk.STATE_NORMAL, COLOR_BLACK)
      self.connect("expose-event", self.redraw)
      self.set_events(
        Gtk.gdk.BUTTON_PRESS_MASK
        |Gtk.gdk.BUTTON_RELEASE_MASK
        |Gtk.gdk.SCROLL_MASK
      )
      if media:
        self.set_media(media, *options)
  def __del__(self):
      self.stop()
  def set_media(self, url, *options):
      self.url = url
      self.pixbuf = None
  def show_image(self):
      # load image
      if self.pixbuf is None:
        print "Loading image:", self.url
        self.pixbuf = Gdk.pixbuf_new_from_file(self.url)
      gc = self.get_style().fg_gc[Gtk.STATE_NORMAL]
      px = self.pixbuf.get_width()
      py = self.pixbuf.get_height()
      wx, wy = self.window.get_size()
      wx = max(wx, 40)
      wy = max(wy, 30)
      # compute aspect
      paspect = float(px)/float(py)
      waspect = float(wx)/float(wy)
      if paspect<waspect:
        ax = int(wy*paspect)
        ay = wy
      else:
        ax = wx
        ay = int(wx/paspect)
      # scale image
      spixbuf = self.pixbuf.scale_simple(ax, ay, Gdk.INTERP_BILINEAR)
      self.window.draw_pixbuf(
        gc, spixbuf, 0, 0,
        (wx-ax)/2, (wy-ay)/2,
        ax, ay
      )
      self.size = (ax, ay)
  def redraw(self, widget, event):
      self.show_image()
  def play(self):
      self.paused = False
      self.show_image()
      self.timer = gobject.timeout_add(2000, self.eof)
      self.state = "Playing"
  def stop(self):
      self.state = "Ended"
      if self.timer is not None:
        gobject.source_remove(self.timer)
  def pause(self, state=None):
      if state is None:
        self.paused = not self.paused
      else:
        self.paused = state
      if self.state=="Playing":
        self.state = "Paused"
      else:
        self.state = "Ended"
  def eof(self):
      if not self.paused:
        self.stop()
  def print_info(self):
      print "URLS:", self.url
      print "State:", self.get_state()

class ImageRefreshWidget(ImagePlayerWidget):
  name = 'imagerefresh'
  def redraw(self, widget, event):
      self.pixbuf = None
      self.show_image()