import sys
if '/usr/scripts' not in sys.path:
    sys.path.append('/usr/scripts')
import tv.dns
Dependencies = ["Time"]



SAP_FILE_URL = "http://tv.crans.org/sap.txt"
BASE_IMAGE_URL = "http://tv.crans.org/images/"
IMAGE_SUFFIX = ".jpg"
SMALL_IMAGE_SUFFIX = "_petites.jpg"


def image_url_for_channel(channel_name, channel_ip, small=0 ):
   if small:
      return BASE_IMAGE_URL + str(channel_ip) + IMAGE_SUFFIX
   else:
      return BASE_IMAGE_URL + str(channel_ip) + SMALL_IMAGE_SUFFIX

def get_channel_list():
   import urllib
   # Getsap file from web sever.
   f = urllib.urlopen(SAP_FILE_URL)
   # Read it.
   s = f.read()
   f.close()

   s = s.split("\n")

   channel_list = []
   for a_line in s:
      try:
         ch_name, ch_ip = a_line.split(":")
         #url = unicode("udp://@%s:1234" % tv.dns.idn(unicode(ch_name, 'utf-8'), True), 'utf-8')
         url = u"https://intranet.crans.org/tv/%s.m3u" % unicode(ch_name, 'utf-8')
         d = {
             "name": ch_name,
             "url": url,
             "image_url": image_url_for_channel( ch_name, ch_ip ),
             "small_image_url": image_url_for_channel( ch_name, ch_ip, small=1 ),
         }
         channel_list.append(d)
      except:
         pass
   return channel_list


def execute(macro, args):
    opt = {"col":4,"cat":False,"ch":False, "width":"10em"}
    # parse args
    if args:
       try:
          for name, value in [(x.split("=")[0].strip(), x.split("=")[1].strip()) for x in args.split(",")]:
             opt[name] = value
       except:
          pass

    IMAGES_PER_LINE = int(opt["col"])
    CATHEGORY = opt["cat"]
    CHANNEL = opt["ch"]
    IMAGE_WIDTH = opt["width"]
    # display all channel
    ch_list = get_channel_list()
    text = macro.formatter.table(1,{})
    i = 0
    for a_channel in ch_list:
        if CATHEGORY:
            if not a_channel["name"].startswith(CATHEGORY):
                continue
        if CHANNEL:
            if a_channel["name"].find(CHANNEL)<0:
                continue
        if i == 0:
           text+= macro.formatter.table_row(1)
        text+= macro.formatter.table_cell(1, {'style':'text-align:center;'})
        text+= macro.formatter.strong( 1 )
        text+= macro.formatter.text( unicode(a_channel["name"], 'utf-8') )
        text+= macro.formatter.strong( 0 )
        text+= macro.formatter.linebreak( 0 )
        #text+= macro.formatter.url(1, href=a_channel["url"], style="text-decoration:none;")
        text+= macro.formatter.url(1, url=a_channel["url"], style="text-decoration:none;")
        text+= macro.formatter.image( src=a_channel["image_url"], alt="", style="width:%s;" % IMAGE_WIDTH )
        text+= macro.formatter.linebreak( 0 )
#        text+= macro.formatter.text( "Regarder maintenant" )
        text+= macro.formatter.url(0)
        text+= macro.formatter.table_cell(0)
        if i == IMAGES_PER_LINE - 1:
           text+= macro.formatter.table_row(0)
        i = (i + 1) % IMAGES_PER_LINE
    while i != 0 and i < IMAGES_PER_LINE:
        text+= macro.formatter.table_cell(1)
        text+= macro.formatter.table_cell(0)
        i += 1
    text+= macro.formatter.table(0)
    return text
