from fnmatch import fnmatch
from sys import platform

if platform == "win32": 
    import os
    os.system("title pgn splitter v1.4")
    os.system("explorer .\\")

splittedList = []
listCSV = []
fileToImport = ""

def start():
    global splittedList
    global listCSV
    splittedList = []
    listCSV = []
    print("Выберите режим импорта исходного текста:")
    choose = input("1. По пути файла .pgn\n 2. По тексту из .pgn\n  0. Выход\n(по умолчанию: 1)\n>>")
    if (choose == "1") or (choose == ""): fileOpen()
    elif choose == "2": textTake()
    elif choose == "0": exit()
    else: 
        print("Некорректный ввод")
        start()

def fileOpen():
    global splittedList, listCSV, fileToImport
    splittedList = []
    listCSV = []
    fileToImport = input("Введите путь импортируемого файла (.pgn):\n>>")
    x = 0
    for i in list(fileToImport):
        if i == ".": x += 1
    if x != 1: 
        fileToImport += ".pgn"
        print("К имеющемуся пути был добален .pgn")
    try:
        with open(fileToImport, "r") as impFile:
            unsplitted = impFile.read()
    except FileNotFoundError:
        print("Файла с таким путём не существует, перезапуск")
        start()
    splitText(unsplitted)

def textTake(): 
    unsplitted = input("Введите строку из .pgn:\n>>")
    splitText(unsplitted)

def splitText(unsplitted):
    x = 0
    tooSplittedList = unsplitted.split(" ")
    for f in tooSplittedList:
        try:
            if fnmatch(f, "*."): splittedList.append(tooSplittedList[x]+";"+tooSplittedList[x+1]+";"+tooSplittedList[x+2])
            x += 1
        except IndexError:
            splittedList.append(tooSplittedList[x]+";"+tooSplittedList[x+1])
    x = 0
    for i in splittedList:
        listCSV.append(splittedList[x]+";")
        x += 1
    exportToFile()
    """fileToExport = input("Введите путь экспортируемого файла (.csv):\n>>")
    x = 0
    for i in list(fileToExport):
        if i == ".": x += 1
    if x != 1: 
        fileToExport += ".csv"
        print("К имеющемуся пути был добален .csv")
    with open(fileToExport, "w") as expFile:
        for item in listCSV:
            expFile.write(str(item) + "\n")
    print("Успешный вывод в файл")"""

def exportToFile():
    global listCSV, fileToImport
    fileToExport = input("Введите путь экспортируемого файла (.csv):\n(по умолчанию: записать в файл .csv в пути импорта)\n>>")
    if fileToExport != "": 
        x = 0
        for i in list(fileToExport):
            if i == ".": x += 1
        if x != 1: 
            fileToExport += ".csv"
            print("К имеющемуся пути был добален .csv")
        with open(fileToExport, "w") as expFile:
            for item in listCSV:
                expFile.write(str(item) + "\n")
    else:
        x = 0
        n = -1
        fileToImportList = list(fileToImport)
        toDelete = []
        for i in fileToImportList:
            n += 1
            if x == 1: toDelete.append(fileToImportList[n])
            if i == ".": 
                x = 1
                toDelete.append(fileToImportList[n])
        for i in reversed(toDelete): 
            fileToImportList.remove(i)
        for i in fileToImportList:
            fileToExport += str(i)
        fileToExport += ".csv"
        with open(fileToExport, "w") as expFile:
            for item in listCSV:
                expFile.write(str(item) + "\n")
    print("Успешный вывод в файл")
    start()

start()