# THIS FILE IS A PART OF VCStudio
# PYTHON 3

import os
w, h = os.get_terminal_size() 

from settings import settings
from settings import talk
from troubleshooter import fix

commands = []
def completer(text, state):
    options = [i for i in commands if i.startswith(text)]
    if state < len(options):
        return options[state]
    else:
        return None

try:
    import readline
    readline.parse_and_bind("tab: complete")
    readline.set_completer(completer)
except:
    print("NO TABS, SORRY!")


def cls():
    #cleaning the terminal
    os.system("clear")
    
    global w
    global h
    
    w, h = os.get_terminal_size()
    if (w % 2) == 0:
        w = w - 1


def output(form, text=""):
    #Basically a fancy print() function
    while len(text) < w:
        text = text + " "
        
    print(form + text)

# COFIGURING LANGUAGE
def lang_setting():
    
    
    
    title = "TYPE YOUR LANGUAGE AND HIT ENTER"
    
    while True:
        
        cls()
        
        #getting the configuration
        language = settings.read("Language")
        
        # Testing if I cal load the language file.
        try:
            open("settings/languages/"+language+".data")
            return
        except:
            pass
        
        talk.alert("Select Language. Look in console.")
        
        # Getting list of available languages
        all_langs = settings.list_languages()
        
        # Make them auto-comelitable
        global commands
        commands = []
        for lang in all_langs:
            commands.append(lang)
        
        # Counting them
        len_langs = len(all_langs)
        
        
        
        
        output("\033[1;44m")
        
        #Title
        
        output("\033[1;44m", \
        " " * int(round((w-len(title))/2)) \
        + title + \
        " " * int((w-len(title))/2) \
        )
        
        output("\033[1;44m")
        
        for raws in range(int((h-5-len_langs)/2)):
            output("\033[1;40m")
        
        for lang in all_langs:
            
            output("\033[1;40m", \
            " " * int(round((w-len(lang))/2)) \
            + lang + \
            " " * int((w-len(lang))/2) \
            )
        
        
        for raws in range(int((h-5-len_langs)/2)):
            output("\033[1;40m")
        
        
    
        print("\033[1;m")
        
        # Trying to write language setting.
        command = input(":")
        if command != "":
            if command not in all_langs:
                title = "THERE IS NO " + command + " FILE"
            else:
                settings.write("Language",command)
                return

        
lang_setting()



def modules_test(Modules, title, setting):
    
    
    # TESTING THAT MODULES ARE INSTALLED CORRECTLY
    
    
        
    cls()
    
    import time  # IK it's crazy but user needs to understand what's
                 # going on. So there be some delay between them.
    
    
    
    
    title = talk.text(title)
        
    
    def drawmodules():
        
        cls()
        
        
        output("\033[1;44m")
    
        output("\033[1;44m", \
        " " * int((w-len(title))/2) \
        + title + \
        " " * int((w-len(title))/2) \
        )
        
        output("\033[1;44m")
        
        for raws in range(int((h-5-len(Modules))/2)):
            output("\033[1;40m")
        
        for mod2 in Modules:
        
            if Modules[mod2] == None:
                
                ans = mod2
                    
                output("\033[1;40m", " "+ans)
            
            elif Modules[mod2] == True:
                ans = mod2 + " "*int(w/2-len(mod2)) + talk.text("checked")
                    
                output("\033[1;42m", " "+ans)
            else:
                
                ans = mod2 + " "*int(w/2-len(mod2)) + talk.text("failed")
                    
                output("\033[1;41m", " "+ans)
                
                
        for raws in range(int((h-6-len(Modules))/2)):
            output("\033[1;40m")
    
    errors = 0
    for mod in Modules:
        
        drawmodules()
            
        try:
            try:
                
                exec( "import " + mod)
                Modules[mod] = True
                
            except:
                Modules[mod] = False
                errors = errors + 1
                
        except:
            pass
        time.sleep(0.1)        
        
            
    drawmodules()
    
    if errors:
        
        global commands
        commands = ["Fix"]
        
        talk.alert(talk.text("missingmodulenotification"))
        
        title = str(errors)+" "+talk.text("missingmoduleserror")
    
        output("\033[1;40m\033[1;31m", \
        " " * int((w-len(title))/2) \
        + title + \
        " " * int((w-len(title))/2) \
        )
        
        #fix thing
        print("\033[1;m")
        command = input(":")
        
        if command == "Fix":
            fix.autofix(Modules)
    
    else:
        #if no errors
        settings.write(setting, "Checked-by-troubleshooter")
        
    print("\033[1;m")
        

Modules = {
        "os":None,
        "gi":None,
        "gi.repository.Gtk":None,
        "gi.repository.GLib":None,
        "cairo":None,
        "PIL":None,
        "PIL.Image":None, 
        "subprocess":None,
        "datetime":None,
        "sys":None,
        "urllib":None,
        "urllib3":None,
        "socket":None,
        "readline":None,
        "json":None,
        "threading":None
        }

modules_test(Modules, "checkingpythonmodules", "Python-is-good")

missing = []

try:
    
    # Let's get the list of files that supposed to be in here.
    
    udata = open("settings/update.data")
    udata = udata.read()
    udata = udata.split("\n")
    
    # Let's parse it
    
    files = []
    
    for f in udata:
        if f and not f.startswith("VERSION") and not f.startswith("[") \
        and not f.startswith("#") and f not in files:
            files.append(f)
    
    Modules = {}
    num = 1
    for  f in sorted(files):
        
        
        
        if num == h-5:
            modules_test(Modules, "checkingpartsoftheprogramm", "VCStudio-is-good")
            Modules = {}
            num = 1
        
        try:
            test = open(f)
            test = test.read()
            
            if f.endswith(".py") and not "import bpy" in test\
                and "-" not in f and f != "run.py" and not "network" in f:
                Modules[f.replace("/", ".")[:-3]] = None
                num += 1
        except:
            if not os.path.exists(os.getcwd()+"/"+f):
                missing.append(f)
    
    modules_test(Modules, "checkingpartsoftheprogramm", "VCStudio-is-good")
    
except:
    i = "settings/update.data"
    ans = i + " "*int(w/2-len(i)) + talk.text("failed")
                
    output("\033[1;41m", " "+ans)
    
for i in missing:
    ans = i + " "*int(w/2-len(i)) + talk.text("failed")
                
    output("\033[1;41m", " "+ans)


desktop = """[Desktop Entry]
Name=VCStudio
GenericName=Blender-Organizer
Path="""+os.getcwd()+"""
Exec=python3 run.py
Icon="""+os.getcwd()+"""/tinyicon.png
Terminal=false
Type=Application
Categories=Graphics;3DGraphics;Office

"""
if os.path.exists(os.environ['HOME']+"/.local/share/applications") \
and not os.path.exists(os.environ['HOME']+"/.local/share/applications/VCStudio.desktop"):
    o = open(os.environ['HOME']+"/.local/share/applications/VCStudio.desktop", "w")
    o.write(desktop)
    o.close()
    output("\033[1;42m", talk.text("desktopcreated"))


print("\033[1;m")