__author__ = 'rvb'
'''
Local Playlist Plugin
(based on ytv plugin by ValdikSS)

plsylist index

http://ip:port/index

m3u playlists

http://ip:port/m3u
http://ip:port/m3u/
http://ip:port/m3u/list-name

plain-tet channel names

http://ip:port/list
http://ip:port/list/
http://ip:port/list/list-name

forward to player

http://ip:port/play/channel-name
http://ip:port/play/list-name/channel-name
http://ip:port/play/{list-name}/(get|mp4|webm)/channel-name

'''
import json
import logging
import urlparse
import urllib
from modules.PluginInterface import VPProxyPlugin
from modules.PlaylistGenerator import PlaylistGenerator
from modules.M3uParser import parseM3U
import config.m3u as config
import os

class M3u(VPProxyPlugin):

    handlers = ('m3u', 'm3ut', 'm3uw', 'm3uo', 'list', 'play', 'index')

    logger = logging.getLogger('plugin_m3u')
    playlist = None

    def handle(self, connection):

        logger = logging.getLogger('plugin_m3u')
        hostport = connection.headers['Host']

        self.splitted_path=connection.path.split('/')

        if self.splitted_path[1]=='m3u':
          prefix='get'
        elif self.splitted_path[1]=='m3uw':
          prefix='ogg'  
        elif self.splitted_path[1]=='m3ut':
          prefix='mp4'  
        elif self.splitted_path[1]=='m3uo':
          prefix='ogv'  
        elif self.splitted_path[1] in ("list","play","index"):
          None  
        else:
          connection.dieWithError(404)  
          return
          
        if len(self.splitted_path)>3 and self.splitted_path[1]!="play":
            connection.dieWithError()
            return

        if self.splitted_path[1]=='index':

            text=""
            for dir in os.walk(config.m3u_directory):
                if dir[0]==config.m3u_directory:
                    for dirname in dir[2]:
                        if dirname.endswith('.m3u'):
                            text=text+'\n'+dirname

            connection.send_response(200)
            connection.send_header('Content-Type', 'text/plain; charset=utf-8')
            connection.end_headers()

            listing = text.encode('utf-8')
            connection.wfile.write(listing) 
                
            return
            
        if len(self.splitted_path)<3 or (len(self.splitted_path)==3 and self.splitted_path[1]=="play"):

           m3u_file=config.m3u_directory+'/'+config.m3u_default

        else:
        
           filename = self.splitted_path[2]
           if filename:
             m3u_file=config.m3u_directory+'/'+self.splitted_path[2]
           else:
             m3u_file=config.m3u_directory+'/'+config.m3u_default

        try:
            playlist=parseM3U(m3u_file)
        except:
            connection.dieWithError(404)
            return    

        if self.splitted_path[1]=="list":
            connection.send_response(200)
            connection.send_header('Content-Type', 'text/plain; charset=utf-8')
            connection.end_headers()
        elif self.splitted_path[1]=="play":
            channel=self.splitted_path[len(self.splitted_path)-1]
            logger.debug('channel requestes= "%s"' % channel)
            if not channel:
              connection.dieWithError(404)
              return
            channel=urllib.unquote(channel).decode('utf-8')
            if len(self.splitted_path)<=4:
              prefix="get"
            elif len(self.splitted_path)==5:  
              prefix=self.splitted_path[len(self.splitted_path)-2]
              if prefix not in ('get','mp4','webm'):
                connection.dieWithError()
                return
            else:
              connection.dieWithError()  
              return
            url=None
            for record in playlist:
              if record.title:
                if record.title.decode('utf-8').replace('/','')==channel:
                    url=record.path.decode('utf-8')
            if url:
                redirect='/'+prefix+'/'+url
                connection.send_response(302)
                connection.send_header('Location', redirect)
                connection.end_headers()
            else:
                logger.debug('Nothing found!')
                connection.dieWithError(404)
                return
            
        else:
            connection.send_response(200)
            connection.send_header('Content-Type', 'application/x-mpegurl')
            connection.end_headers()

        try:
            playlist=parseM3U(m3u_file)
        except:
            connection.dieWithError(404)
            return    

        if not playlist:
            connection.dieWithError()
            return

        exported = ""

        if self.splitted_path[1]=="list":
 
             for record in playlist:
                 if record.title:
                     exported = exported + "" + record.title.decode('utf-8').replace('/','') + "\n"
        
        else:    

            playlistgen = PlaylistGenerator()

            for record in playlist:
                if record.title:
                    channel=dict()
                    channel['name']=record.title.decode('utf-8')
                    channel['url']=record.path.decode('utf-8')            
                    try:
                      channel['tvg']=record.attrs['tvg-name'].decode('utf-8')
                    except:
                      None
                    try: 
                      if record.attrs['group-title'] != 'None':   
                        channel['group']=record.attrs['group-title'].decode('utf-8')
                    except:
                      None
                    try:    
                      channel['country']=record.attrs['country'].decode('utf-8')
                    except:
                      None
                    try:    
                      channel['logo']=record.attrs['tvg-logo'].decode('utf-8')
                    except:
                      None
                    playlistgen.addItem(channel)

            exported = playlistgen.exportm3u(hostport,prefix)

        if exported:
            exported = exported.encode('utf-8')
            connection.wfile.write(exported)

    def getparam(self, key):
        if key in self.params:
            return self.params[key][0]
        else:
            return None
