import os
import glob

scriptDir = os.getcwd()

def getKickedAbsPath():
    '''
    Returns Kicked's absolute path and goes back to the scrip's path
    '''
    os.chdir('..')
    path = os.getcwd()
    os.chdir(scriptDir)
    return path

def getFootprinLibraries():
    '''
    Returns the list of all .pretty footprint files and goes back to the scrip's path
    '''
    footpintPath = os.path.join(getKickedAbsPath(), "footprints")
    os.chdir(footpintPath)

    footprintList = []
    prettyFiles = os.listdir()

    # append all .pretty folders
    for f in prettyFiles:
        if f.endswith(".pretty"):
            footprintList.append(f)

    os.chdir(scriptDir)
    return footprintList


def getSymbolLibraries():
    '''
    Returns the list of all .kicad_sym simbol files and goes back to the scrip's path
    '''
    symbolPath = os.path.join(getKickedAbsPath(), "symbols")
    os.chdir(symbolPath)

    symboList = []
    symFiles = os.listdir()
    symbolList = []
    # append all .pretty folders
    for f in symFiles:
        if f.endswith(".kicad_sym"):
            symbolList.append(f)

    os.chdir(scriptDir)
    return symbolList


# Gets the inital paths required
footprintLibraries = getFootprinLibraries()
symbolLibraries = getSymbolLibraries()

# User input to get the path to the project
pathToProjectFolder = input("enter path to KiCad project folder:")

# create relative path from KiCad project and the KicED library
relative_path = os.path.relpath(getKickedAbsPath(),pathToProjectFolder)

# Translates the relative paht ot what kicad project needs from kiced
baseRelativeBasePath = os.path.join("${KIPRJMOD}", relative_path)


temp = []
for item in footprintLibraries:
    pth = os.path.join(baseRelativeBasePath, "footprints")
    tmp = os.path.join(pth, item)
    temp.append(tmp)
footprintLibPaths = temp

temp = []
for item in symbolLibraries:
    pth = os.path.join(baseRelativeBasePath, "symbols")
    tmp = os.path.join(pth,item)
    temp.append(tmp)
symbolLibPaths = temp

# INFO PRINT #
print("Selected Project Path:")
print(pathToProjectFolder)
print("Curent Working Path:")
print(scriptDir)
print("Relative path from Project to Kiced:")
print(relative_path)
print("Formated relative path to kiced library relative to project directory")
print(baseRelativeBasePath)
print("Including following libraries:")
for f in footprintLibPaths:
    print(f)

for f in symbolLibPaths:
    print(f)


# creating footprint lib link file
os.chdir(pathToProjectFolder)
try:
    with open("fp-lib-table",'w') as file:
        file.write("(fp_lib_table\n  (version 7)\n")

        if 1:
            for p in footprintLibPaths:
                p = p.replace("\\","/")
                # example
                # (lib (name "000_SDM_Resistor")(type "KiCad")(uri "${KIPRJMOD}/test_lib/footprints/000_SDM_Resistor.pretty")(options "")(descr ""))
                file.write("  (lib (name \"")
                temp = os.path.basename(p)
                file.write(temp[:-len(".pretty")])
                file.write("\")(type \"KiCad\")(uri \"")
                file.write(p)
                file.write("\")(options \"\")(descr \"\"))\n")

        file.write(")")
        os.chdir(scriptDir)
except FileNotFoundError:
    print("fail")
    os.chdir(scriptDir)

# creating symbol lib link file
os.chdir(pathToProjectFolder)
try:
    with open("sym-lib-table",'w') as file:
        file.write("(sym_lib_table\n  (version 7)\n")

        if 1:
            for p in symbolLibPaths:
                p = p.replace("\\","/")
                # example
                # (lib (name "000_SDM_Resistor")(type "KiCad")(uri "C:/Users/Edwin/Documents/19_git/00_KiCad_Projects/KicED/footprints/000_SDM_Resistor.pretty")(options "")(descr ""))
                file.write("  (lib (name \"")
                temp = os.path.basename(p)
                file.write(temp[:-len(".kicad_sym")])
                file.write("\")(type \"KiCad\")(uri \"")
                file.write(p)
                file.write("\")(options \"\")(descr \"\"))\n")

        file.write(")")
        os.chdir(scriptDir)
except FileNotFoundError:
    print("fail")
    os.chdir(scriptDir)

print("Import Done!")
