import os
import re
import time
import urllib.request

MINUTES = 3 #download if list is older

def get_url(url, fn):
    if os.path.isfile(fn):
        os.remove(fn)
    try:
        urllib.request.urlretrieve(url, fn)
    except:
        pass
        
def file_aged(fn):
    if os.path.isfile(fn):
        age = int(time.time() - os.stat(fn).st_mtime)
        return age > MINUTES*60
    else:
        return True

list_url = 'https://sourceforge.net/p/synwrite/wiki/Registry/raw'
list_regex = "text=\w?('.*?'\s)"
list_fn = os.path.join(os.getenv('TEMP'), 'synwrite_plugins.txt')

def get_item_url(item):
    try:
        url = 'http://sourceforge.net/projects/synwrite-addons/files/' + item + '/download'
        res = urllib.request.urlopen(url)
        return res.geturl()
    except:
        return

def get_plugins_list():
    fn = list_fn
    if file_aged(fn):
        get_url(list_url, fn)
    if not os.path.isfile(fn):
        return "CantGetList"
    
    s = open(fn).read()

    s = s.replace('\n', '')
    s = s.replace('  ', ' ')
    
    r = re.compile(list_regex, re.S)
    if not r: return "CantCompileRegex"
    rr = r.search(s)
    if not rr: return "CantParseList"
    s = rr.group(1)
    s = eval(s)
    
    items = s.split('\r\n')
    last = False
    for i in range(len(items)):
        if items[0].startswith('--'):
            last = True
        del items[0]
        if last: break

    items = sorted(items)
    res = []
    for s in items:
        if '|' in s:
            props = s.split('|')
            props = [l.strip() for l in props]
            res += [props]
    return res
    

if __name__ == '__main__':
    url = 'PyPlugins/kvichans.BackupFile/plugin.kvichans.BackupFile.zip'
#    print('Url:')
#    print(get_item_url(url))
    
    items = get_plugins_list()
    if type(items)==str:
        print(items)
    else:
        print('List:')
        for l in items:
            print(l)
