import sys
import json
from tkinter import filedialog

def getFiles(failedargs):
    newfiles = []
    
    if failedargs:
        if failedargs == -1:
            answer = input("""\
You didn't specify any files as input, would you like to continue? y/n
>""")
            if answer in ["n", ""]:
                raise SystemExit
        else:
            answer = input("""\
One or more of the command line arguments couldn't be opened, would you like to
specify additional input files? y/n
>""")
            if answer in ["n", ""]:
                return newfiles, -1
    
    prompt = """\
Please select the filename of one of the files you want to input to this
script, or hit enter with the filename box empty to finish."""
    
    filename = "foo"
    while filename:
        print(prompt)
        
        filename = filedialog.askopenfilename()
        
        if filename:
            try:
                with open(filename) as f:
                    pass
            except OSError as e:
                error = """\
Input failed for filename "%s".""" % file
                print(error % file)
                print(e)
            else:
                newfiles.append(filename)
    
    return newfiles, -1

def getFormats(files):
    neededKeys = ["prefix", "catchall", "keywords", "sep"]
    default = {"prefix" : "##",
               "catchall" : "!!",
               "keywords" : ["game", "program", "task", "notes"],
               "sep" : ","}
    answer = "foo"
    formatList = []
    for file in files:
        if answer not in "dD":
            answer = input("""\
Would you like to select a JSON file to serve as the format specifier for:
    {0}
or would you like to use the default format?
    prefix: "{1[prefix]}"
    catchall: "{1[catchall]}"
    keywords: "{1[keywords]!s}"
    (keyword) sep(arator) : "{1[sep]}"

Your options are:
    Y: Yes, select a format specifier
    N: No, but continue asking, I might for a later file
    S: Enter from scratch
    D: No, use the default format for all files
If you successfully load or enter a format, you'll have the option of setting
it as the default for the remaining files. If your load attempt is
unsuccessful, you can either try again, do it from scratch, or quit the script.
> """.format(file, default))
            if answer not in ["y", "Y", "n", "N", "d", "D", "s", "S"]:
                answer = "n"
                print("Didn't get that, so I'll assume \"no.\"")
                formatList.append(default)
            elif answer in "yY":
                while True:
                    formatFilename = filedialog.askopenfilename()
                    
                    try:
                        with open(formatFilename) as f:
                            temp = json.load(f)
                    except OSError as e:
                        error = """\
Input failed for filename "%s".""" % formatFilename
                        print(error)
                        print(e)
                        temp = {}
                        
                        if keepTrying(file) == "s":
                            for key in neededKeys:
                                temp[key] = scratch(key)
                            
                            if keepFormat(temp):
                                default = temp
                                
                            formatList.append(temp)
                            
                        elif keepTrying:
                            continue
                        else:
                            formatList.append(default)
                    except ValueError as e:
                        error = """\
"%s" doesn't appear to be properly formatted for JSON deserialization.\
""" % formatFilename
                        print(error)
                        print(e)
                        temp = {}
                        
                        if keepTrying(file) == "s":
                            for key in neededKeys:
                                temp[key] = scratch(key)
                            if keepFormat(temp):
                                default = temp
                            formatList.append(temp)
                        elif keepTrying:
                            continue
                        else:
                            formatList.append(default)
                    else:
                        missing = []
                        incorrectKeywords = False
                        
                        for key in neededKeys:
                            if key in temp:
                                if key == "keywords":
                                    if type(temp[key]) != type([]):
                                        incorrectKeywords = True
                            else:
                                missing.append(key)
                        
                        if missing:
                            for item in missing:
                                print("Key %s is not in the object loaded."