#!python

from MythTV.wikiscripts import *
from time import time
import os.path
import sys

def get_input(comment, items):
    while True:
        print('  0: Exit')
        for i,item in enumerate(items):
            print('  {0}: {1}'.format(i+1, item))
        print(comment)

        while True:
            try:
                i = input('> ')
                if i == 'list':
                    break
                elif i in ('exit','0'):
                    return -1

                i = int(i)-1
                if i in range(len(items)):
                    return i
                print("Selection is outside range. Use 'list' to list options.")

            except KeyboardInterrupt:
                sys.exit()
            except EOFError:
                sys.exit()
            except:
                print('This input only accepts integers.  Use Ctrl-C to exit')

def selectCat(catlist):
    keys = list(catlist.keys())
    while True:
        inp = get_input('Please choose a category.', keys)
        if inp == -1:
            return
        selectScript(catlist[keys[inp]])

def selectScript(scriptlist):
    names = [s.info.name for s in scriptlist]
    while True:
        inp = get_input('Please choose a script.', names)
        if inp == -1:
            return
        saveScript(scriptlist[inp])

def saveScript(script):
    print('Author:      '+script.info.author)
    print('Description: '+script.info.long)
    print('Webpage:     '+script.info.webpage)

    for name in list(script.code.keys()):
        if name[0] in ('/', '~'):
            path = name
        else:
            path = '~/bin/'+name

        try:
            inp = input('Save to [{0}]:'.format(path))
        except EOFError:
            sys.exit()
        except KeyboardInterrupt:
            continue
        except:
            sys.exit()

        if len(inp):
            path = inp

        dir = os.path.dirname(os.path.expanduser(path))
        if not os.path.exists(dir):
            os.makedirs(dir)
        script.saveScript(name, os.path.expanduser(path))

if __name__ == '__main__':
    print("MythTV Interactive Script Downloader.")
    print("This script parses the wiki, and may take several minutes.")
    tic = time()
    tmp = Script.getAll()
    print('Loading took %0.2f seconds' % (time()-tic))

    scripts = {}
    for script in tmp:
        for cat in script.category:
            if cat in ('Articles with unsupported titles',
                       'HOWTO'):
                continue
            if cat not in scripts:
                scripts[cat] = []
            scripts[cat].append(script)

    selectCat(scripts)
