# -*- 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 re

import gobject

from TimeSpan import TimeSpan

class Program:
    def __init__(self, program):
        self.title = self.__get_title(program)
        self.markup_escaped_title = gobject.markup_escape_text(self.title)
        self.description = self.__get_description(program)
        start = self.__get_datetime(program, "start")
        stop = self.__get_datetime(program, "stop")
        self.start_time = start.strftime("%X")[:5]
        self.stop_time = stop.strftime("%X")[:5]
        self.date = start.strftime("%a, %b %d").encode("utf-8")
        self.time_span = TimeSpan(start, stop)

    def __cmp__(self, other):
        return cmp(self.time_span.start, other.time_span.start)

    def __str__(self):
        return self.title

    def __get_title(self, program):
        return unicode(program["title"][0][0]).encode("utf-8")

    def __get_description(self, program):
        if program.has_key("desc"):
            description = unicode(program["desc"][0][0]).encode("utf-8")
            return description
        return ""

    def __get_datetime(self, program, time):
        time_re = re.compile(r"(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)")
        match = time_re.match(program[time])
        ints = [int(x) for x in match.groups()]
        return datetime.datetime(*ints)

    def get_time_until_start(self):
        return self.time_span.time_until_start()

    def get_time_until_stop(self):
        return self.time_span.time_until_stop()

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