# -*- coding: utf-8 -*-

# Copyright (C) 2004-2007 Johan Svedberg <johan@svedberg.com>

# This file is part of ontv.

# ontv 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.

# ontv 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 ontv; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA

import datetime
import os.path
import thread
import urllib
import sys
from gettext import gettext as _

import gtk
import gtk.gdk
import gobject

import GUI
from ontv import IMAGES_DIR

class Channel:
    def __init__(self, channel, xmltvfile):
        self.id = channel["id"]
        self.name = self.__get_name(channel)
        self.markup_escaped_name = gobject.markup_escape_text(self.name)
        self.icon = self.__get_icon(channel)

        self.logo_file = ""
        self.logo = None
        self.logo_small = None
        self.custom_logo = False

        self.selected = False
        self.programs = []

        if self.icon and not xmltvfile.listings.channel_has_custom_logo(self):
            thread.start_new_thread(self.__download_logo, (self.icon,
                                                           xmltvfile,))

    def __cmp__(self, other):
        return cmp(self.name, other.name)

    def __str__(self):
        return self.name

    def __getstate__(self):
        dict = self.__dict__.copy()
        if dict["logo"]:
            del dict["logo"]
        if dict["logo_small"]:
            del dict["logo_small"]
        return dict

    def __setstate__(self, dict):
        self.logo = self.logo_small = None
        self.set_logo(dict["logo_file"])
        self.__dict__.update(dict)

    def __get_name(self, channel):
        if channel.has_key("display-name"):
            return unicode(channel["display-name"][0][0]).encode("utf-8")
        return None

    def __get_icon(self, channel):
        if channel.has_key("icon"):
            return channel["icon"][0]["src"]
        return None

    def __download_logo(self, icon, xmltvfile):
        self.set_logo(os.path.join(IMAGES_DIR, "ontv-logo-downloading.png"))
        gtk.gdk.threads_enter()
        xmltvfile.emit("downloading-logo", (self))
        gtk.gdk.threads_leave()
        config = xmltvfile.config

        if config.debug:
            print("Downloading logo for channel \"%s\" from:\n%s..." %
                  (self.name, icon))
        try:
            file = os.path.join(config.logos_dir, os.path.basename(icon))
            (self.logo_file, headers) = urllib.urlretrieve(icon, file)

        except IOError, ioe:
            print >> sys.stderr, "Unable to download logo for channel \
                                  \"%s\" from:\n%s: %s" % (self.name, icon,
                                 ioe.strerror)

        self.set_logo(self.logo_file)
        gtk.gdk.threads_enter()
        xmltvfile.emit("downloading-logo-done", (self))
        gtk.gdk.threads_leave()

    def set_logo(self, file_name, silent=True):
        if os.path.exists(file_name):
            try:
                logo_pixbuf = gtk.gdk.pixbuf_new_from_file(file_name)
            except gobject.GError, ge:
                if silent:
                    self.logo = None
                    self.logo_small = None
                    return
                self.custom_logo = False
                ed = GUI.ErrorDialog(_("Error while loading %s" % file_name),
                                     ge.message)
                ed.run()
                ed.destroy()
                return

            self.logo = logo_pixbuf.scale_simple(48, 48,
                                                 gtk.gdk.INTERP_BILINEAR)
            self.logo_small = logo_pixbuf.scale_simple(24, 24,
                                                       gtk.gdk.INTERP_BILINEAR)

    def get_current_program(self):
        for program in self.programs:
            if program.time_span.spans_now():
                return program
        return None

    def get_upcoming_program(self):
        for program in self.programs:
            if program.time_span.start > datetime.datetime.now():
                return program
        return None

# vim: set sw=4 et sts=4 tw=79 fo+=l:
