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

# Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php

# Copyright 2009, Jose Luis Garduno Garcia <deepsight[atsign]gmail.com>
# Based on the Lolcats Media backend from Benjamin Kampmann
# Copyright 2008, Benjamin Kampmann <ben.kampmann@googlemail.com>

"""
This is a Media Backend that allows you to access video streams from 
a Dreambox which uses the Enigma2 web interface. Based on the
Lolcats media backend.

"""
import urllib

from coherence.backend import BackendStore
from coherence.backend import BackendItem
from coherence.upnp.core import DIDLLite
from coherence.upnp.core.utils import getPage
from twisted.internet import reactor
from coherence.extern.et import parse_xml

class TVChannel(BackendItem):

    def __init__(self, parent_id, id, title, url):
        self.parentid = parent_id       
        self.update_id = 0
        self.id = id                    
        self.location = url             
        self.name = title              
        self.item = DIDLLite.VideoItem(id, parent_id, self.name)
        res = DIDLLite.Resource(self.location, 'http-get:*:video/mpeg:DLNA_PN=MPEG_PS_PAL')
        res.size = None 
        self.item.res.append(res)


class TVChannelsContainer(BackendItem):

    def __init__(self, parent_id, id):
        self.parent_id = parent_id
        self.id = id
        self.name = 'Dreambox'
        self.mimetype = 'directory'
        self.update_id = 0
        self.children = []
        self.item = DIDLLite.Container(id, parent_id, self.name)
        self.item.childCount = None 

    def get_children(self, start=0, end=0):
        if end != 0:
            return self.children[start:end]
        return self.children[start:]

    def get_child_count(self):
        return len(self.children)

    def get_item(self):
        return self.item

    def get_name(self):
        return self.name

    def get_id(self):
        return self.id

class DreamboxStore(BackendStore):

    implements = ['MediaServer']  

    def __init__(self, server, *args, **kwargs):
        self.ROOT_ID = 0
        self.server = server
        
        #streaminghost is the ip address of the dreambox machine, defaults to localhost 
        self.streaminghost = kwargs.get('streaminghost',self.server.coherence.hostname) 
        
        self.name = kwargs.get('name', 'Dreambox')
        # timeout between updates in minutes
        self.refresh = float(kwargs.get('refresh', 1)) * 60
        
        #for an explanation of bref see http://dream.reichholf.net/wiki/Enigma2:WebInterface
        self.bRef = kwargs.get('bRef','1:0:1:5DE:23:46:E080000:0:0:0:')
        
        self.rss_url = "http://" + self.streaminghost + "/web/epgnow?bRef=" + urllib.quote(self.bRef)
        
        print urllib.quote(self.bRef)
        self.next_id = 1000

        self.last_updated = None
        self.container = TVChannelsContainer(None, self.ROOT_ID)
        self.channels = {}
        dfr = self.update_data()
        dfr.addCallback(self.init_completed)

    def get_by_id(self, id):
        
        try:
            id = int(id)
            if id == self.ROOT_ID:               
                return self.container
            else:
                return self.channels[id]
        
        except:        
            return self.container

    def upnp_init(self):
        if self.server:

            self.server.connection_manager_server.set_variable( \
                0, 'SourceProtocolInfo', ['http-get:*:video/mpeg:DLNA_PN=MPEG_PS_PAL',
                'http-get:*:video/mpeg:DLNA_PN=MPEG_TS_PAL',])

    def update_data(self):
        dfr = getPage(self.rss_url)
        dfr.addCallback(parse_xml)
        dfr.addCallback(self.parse_data)
        dfr.addBoth(self.queue_update)

        return dfr

    def parse_data(self, xml_data):
        root = xml_data.getroot()
        
        print len(root)
        self.container.children = []
        self.channels = {}

        for y in root:
            if y.tag == "e2event":
                title = y[-1].text + ' | ' 
                            
                try:
                    title += y[-5].text
                    print title
                
                except:
                    print "some error getting the title"
                    

                url = 'http://' + self.streaminghost +':8001/' + y[-2].text
                print title, url 
                channel = TVChannel(self.ROOT_ID, self.next_id, title, url)
                self.container.children.append(channel)
                self.channels[self.next_id] = channel
                self.next_id += 1

        self.container.update_id += 1
        self.update_id += 1

        if self.server:
            self.server.content_directory_server.set_variable(0, 'SystemUpdateID', self.update_id)
            value = (self.ROOT_ID,self.container.update_id)
            self.server.content_directory_server.set_variable(0, 'ContainerUpdateIDs', value)

    def queue_update(self, error_or_failure):
        reactor.callLater(self.refresh, self.update_data)
