#!/usr/bin/env python3
import json
import sys
from subprocess import call
import os
import readline
import Vctrl
import colors as c
import emoji as e
import time
import shutil
width, height = shutil.get_terminal_size()


print("your terminal's width/height", width, height)
print("\033c")
begin_msg='''
 _____ _     ____  ____  _     ____  ____  ____  ____  ____ 
/    // \   /  _ \/ ___\/ \ /|/   _\/  _ \/  __\/  _ \/ ___\\
|  __\| |   | / \||    \| |_|||  /  | / \||  \/|| | \||    \\
| |   | |_/\| |-||\___ || | |||  \_ | |-|||    /| |_/|\___ |
\_/   \____/\_/ \|\____/\_/ \|\____/\_/ \|\_/\_\\\\____/\____/
                                                                     
'''
f_begin_msg = begin_msg.center(len(begin_msg), "0")
print(f_begin_msg)
time.sleep(1)
print("\033c")
Vctl = Vctrl.Verctrl()

FDIR = os.getcwd()
template = '''
{
    "flashcards": [
        {
            "hi": "test1"
        }
    ]
}

'''

home=os.environ['HOME']
os.chdir(home)

try:
    kfg = open(home + '/.fconfig.json')
except FileNotFoundError:
    os.chdir(home)
    newconfig = open(".fconfig.json", 'w+')
    newconfig.write(
'''{
    "sets": "/home/error/sets"
}''')

cfg = open(home + '/.fconfig.json')


config=json.load(cfg)
sets=config['sets']

def createSet(name):
    os.chdir(sets)
    f = 0
    if name.endswith('.json'):
        f = open(name, 'w+')
        f.write(template)
        f.close()
        call(['vim', name])
    else:
        f = open(name + '.json', 'w+')
        f.write(template)
        f.close()
        call(['vim', name + '.json'])   

FILES=[]

def deleteSet():
    os.chdir(sets)
    readline.parse_and_bind("tab: complete")
    readline.set_completer(complete)
    openme=input(c.m+"what file do you want to delete(type none to delete nothing):"+c.y)
    if not openme.endswith('.json'):
        openme = openme + '.json'
    if not openme == 'none':
        call(['rm', openme])
    else:
        sys.exit()

def complete(text, state):
    FILES=os.listdir()
    for cmd in FILES:
        if cmd.startswith(text):
            if not state:
                return cmd
            else:
                state -= 1
def startFlashcards():
    os.chdir(sets)
    readline.parse_and_bind("tab: complete")
    readline.set_completer(complete)
    openme=input(c.m+"what file do you want to open:"+c.y)
    if not openme.endswith('.json'):
        openme = openme+'.json'
    with open(openme) as myset:
        data = json.load(myset)
        fc = data["flashcards"]
        for card in fc: 
            for key in card:
                bnswer = input(c.m+key + ":\n"+c.y)
                cnswer = bnswer.lstrip()
                answer = cnswer.rstrip()
                if answer == card[key]:
                    print(c.g+"Good Job, "+e.blush)
                else:
                    print(c.r+"Wrong "+e.broken_heart+", the answer was:" + card[key] + ". Your answer:" + answer)
AllSets = []
def findAndSearch():
    for root, subFolders, files in os.walk(home):
        if "sets" in root:
            AllSets.append(root)
    readline.parse_and_bind("tab: complete")
    readline.set_completer(complete)
    for Set in AllSets:
        print(c.g+Set)
    global sets
    sets = input(c.m+"what is your sets directory(it can only be in home or and subdirectory of home), if you have no sets file, run \"mkdir ~/sets\" "+c.y)


#test if there is a sets dir and check it against the config file
#if the sets dir has been moved, search for it. and notify the user

try:
    open(sets)
except FileNotFoundError:
    findAndSearch()
except IsADirectoryError:
    setsIsNormal=True
#get all args besides how the file is run, and allow them to be compared
if not config['sets'] == sets:
    os.remove(home + '/.fconfig.json')
    os.chdir(home)
    newconfig = open(".fconfig.json", 'w+')
    newconfig.write('''        
    {
    "sets": "''' + sets + '''"
    }''')
i = 0

os.chdir(sets)
updated = Vctl.check_version("https://github.com/17liamnaddell/fcards-python", sets)

with open(sets + "/VERSION") as version:
    if version.read() == updated:
        pass
    else:
        version.close()
        print(c.g+"updated")
        #os.remove(sets + "/VERSION")
        f = open(sets + "/VERSION", "w+")
        f.write(updated)
        os.chdir(sets)
        Vctl.update_and_end(FDIR, sets)
for arg in sys.argv:
    if arg == "-s":
        name = sys.argv[i+1]
        createSet(name)
    elif arg == "-r":
        startFlashcards()
    elif arg == "-d":
        deleteSet()
    elif arg == "-l":
        os.chdir(sets)
        for filez in os.listdir():
            print(c.y+filez)
    try:
        sys.argv[1]
    except IndexError:
        print(c.r+"Bad args, to delete a set, use -d, to list the sets, use -l, to run the program, enter -r, to create a flashcard set, enter -s <name> ")
        sys.exit()
    i += 1 

