

# Generic functions
def findInfo(tag, s):
    end = '"'
    if (s.find(tag)>-1):
        t = s[s.find(tag)+len(tag)+2:s.rfind(end)]
        return  t[0:t.find(end)]
    else:
        return ""




def download_logo():
    
    path_filename = 'source.m3u'
    
    # Process the m3u file
    f = open(path_filename, "r", encoding="utf8")
    Lines = f.readlines()
    print('ouverture fichier', flush=True)
    channel = {}
    separator = '--------'
    topic = ''
    num_channel = 0
    for line in Lines:
        #print(line,flush=True)

        if separator in line:
            topic = line[10:]
            topic = topic.replace(separator,'')

        if len(channel)>0 and line[0:4]=="http":

            print ('download ' + channel['urlLogo'])
            #new_channels.append(channel)
            #print(channel,  flush=True)

        if line[0:4] == "#EXT":
            channel = {}

            # DEFINE CHANNEL NAME
            name_channel = line[line.rfind(',')+1:].strip('\n')
    
            channel_exist = False
            if len(name_channel)>0:                   
                channel = {"Name":name_channel, "Topic":topic, "urlLogo" : findInfo('tvg-logo', line)}
                num_channel += 1
                channel_exist = True

            if channel_exist == False:
                name_channel = line[line.rfind('|')+2:].strip('\n')
                if len(name_channel) > 0:
                        channel = {"Name":name_channel, "Topic":topic, "urlLogo" : findInfo('tvg-logo', line)}


    result = {'num_channel': num_channel}

    return result