# -*- coding: utf-8 -*-
import os, codecs


def file_to_dict(fichier,defautDict):    
    try:
        f = codecs.open(fichier,'r','utf-8')
    except:
        return defautDict
    lines=f.readlines()
    f.close()
    ret = defautDict
    for line in lines:
        line = line.strip()
        if line and line[0] != "#":
            values = line.split("=")
            ret[values[0]] = values[1].replace('\"','')
    return ret

def file_to_tag_list(fichier,defautList):
    try:
        f = codecs.open(fichier,'r','utf-8')
    except:
        return defautList
    lines=f.readlines()
    f.close()
    tags = [[],[]]
    for line in lines:
        line = line.strip()
        if line and line[0] != "#":
            values = line.split("!!!")
            tags[0].append(values[0])
            tags[1].append(values[1])
    return tags

def gimme_my_settings():
    """Give preferences"""
    #First of all, create a .partielator dir in the home folder if it doesn't exist
    #and delete .partielator if it's a file (old version worked with a .partielator file)
    #Tells if a .partielator dir was found so as to know if the wizard must be shown
    home_dir = os.path.expanduser("~")
    first_time = False
    if ".partielator" in os.listdir(home_dir):
        if os.path.isfile(os.path.join(home_dir,".partielator")):
            os.remove(os.path.join(home_dir,".partielator"))
            os.mkdir(os.path.join(home_dir,".partielator"))
            first_time = True
        if not "generate" in os.listdir(os.path.join(home_dir,".partielator")):
            os.mkdir(os.path.join(home_dir,".partielator","generate"))
    else:
        os.mkdir(os.path.join(home_dir,".partielator"))
        os.mkdir(os.path.join(home_dir,".partielator","generate"))
        first_time = True

    #Get basic settings in a dictionnary
    fichier = os.path.join(home_dir,".partielator","basics")
    defautDict = { "file_viewer" : "xdvi",\
               "type_of_file" : "dvi",\
               "save_location" : home_dir,\
               "tex_path" : home_dir,\
               "use_preview" : "True",\
               "little_splitter_s1" : "200",\
               "little_splitter_s2" : "250",\
               "big_splitter_s1" : "450",\
               "big_splitter_s2" : "550",\
               "height" : "550",\
               "width" : "1000",\
               "lang" : "en"}
    dictionnary = file_to_dict(fichier,defautDict)

    #Get header
    try:
        f = codecs.open(os.path.join(home_dir,".partielator","header"),'r','utf-8')
        header = ""
        for l in f.readlines():
            header += l
    except:
        header = "\\documentclass{article}"
    
    #Get tags
    defautList = [["\\begin{exercise}"],["\\end{exercise}"]]
    fichier = os.path.join(home_dir,".partielator","tags")
    tags = file_to_tag_list(fichier,defautList)
    
    #Get compile sequence
    try:
        compile_seq = []
        f = codecs.open(os.path.join(home_dir,".partielator","compile_seq"),'r','utf-8')
        for i in f.readlines():
            compile_seq.append(i.replace("\n",""))
    except:
        compile_seq = ["latex -halt-on-error -output-directory=/tmp/partielator !file.tex",\
                       "dvipng !file.dvi -o !file.png"]
    
    
    #Get generate files
    generate = {"Same header" : header}
    generate["Add ..."] = ""
    for i in os.listdir(os.path.join(home_dir,".partielator","generate")):
        try:
            f = codecs.open(os.path.join(home_dir,".partielator","generate",i),'r','utf-8')
            generate[i] = ""
            for l in f:
                generate[i] += l
        except:
            print("couldn't process file "+f)

    return first_time, tags, header, dictionnary, compile_seq, generate



if __name__ == "__main__":
    tags, header, dictionnary, compile_seq, generate = gimme_my_settings()
    print generate["basics"]



