import os
import json
import asyncio
import googletrans

def load_file_translations():
    languages = {}
    full_languages = {}
    for (dirpath, dirnames, filenames) in os.walk(os.path.join("phoscon_app","language")):
        for file in filenames:
            if file.endswith(".json"):
                with open(os.path.join(dirpath,file),"r",encoding="utf8") as f:
                    language = dirpath.split("\\")[-1]
                    data = {}
                    try:
                        data = json.load(f)
                    except Exception as e:
                        pass
                        # print(f"\033[91m[Error]: Skipping file {os.path.join(dirpath,file)} | {e} \033[0m")

                    if language not in languages:
                        languages[language] = []
                    if language not in full_languages:
                        full_languages[language] = {}
                    
                    languages[language] += data.keys()
                    for key in data.keys():
                        full_languages[language][key] = {"translation":data[key],"file":file}

    return languages,full_languages

def scan_for_translate_ids():
    manuel_translate_ids = []
    auto_translate_ids = []

    # Scan all .html and .inc files in phoscon_app-src
    for (dirpath, dirnames, filenames) in os.walk(os.path.join("phoscon_app-src")):
        for file in filenames:
            if file.endswith((".inc",".html")):
                with open(os.path.join(dirpath,file),"r",encoding="utf8") as f:
                    file_content = f.read()
                    # print(f"Scanning file: {dirpath+"/"+file}, size: {len(file_content)}")
                    
                    # Splitting for data-translateid
                    for data in file_content.split("data-translateid")[1:]:
                        data = data.replace(" = ","=")
                        if data[1] == "'":
                            data = data.replace("'",'"')
                        translate_id = data.split('"')[1]
                        if "%" in translate_id:
                            if (translate_id,dirpath+"/"+file) not in manuel_translate_ids:
                                manuel_translate_ids.append((translate_id,dirpath+"/"+file))
                        else:
                            if translate_id not in auto_translate_ids:
                                auto_translate_ids.append(translate_id)
                    
                    # Splitting for translate
                    for data in file_content.split("translate(")[1:]:
                        if data[0] == "'":
                            data = data.replace("'",'"')
                        elif data[0] != '"' and not (data[0].isnumeric() or data[0] == "-"):
                            if (translate_id,dirpath+"/"+file) not in manuel_translate_ids:
                                manuel_translate_ids.append((translate_id,dirpath+"/"+file))
                        translate_id = data.split('"')[1]
                        if "%" in translate_id:
                            if (translate_id,dirpath+"/"+file) not in manuel_translate_ids:
                                manuel_translate_ids.append((translate_id,dirpath+"/"+file))
                        else:
                            if translate_id not in auto_translate_ids:
                                auto_translate_ids.append(translate_id)

    # Scan all .html and .inc files in phoscon_app/js
    for (dirpath, dirnames, filenames) in os.walk(os.path.join("phoscon_app","js")):
        for file in filenames:
            if file.endswith((".js")):
                with open(os.path.join(dirpath,file),"r",encoding="utf8") as f:
                    file_content = f.read()
                    
                    # Splitting for data-translateid
                    for data in file_content.split("data-translateid")[1:]:
                        
                        # data-translateid="xxx"
                        if data.startswith(" = "):
                            data = data.replace(" = ","=")
                        
                        if data[0] == "=":
                            if data[1] == "'" or data[1] == '"':
                                separator = data[1]
                            
                                translate_id = data.split(separator)[1]

                                for char in ["%","+","(",")","-","?","."]:
                                    if char in translate_id:
                                        if (translate_id,dirpath+"/"+file) not in manuel_translate_ids:
                                            manuel_translate_ids.append((translate_id,dirpath+"/"+file))
                                        break
                                else:
                                    if translate_id not in auto_translate_ids:
                                        auto_translate_ids.append(translate_id)

                        # ("data-translateid","xxx")
                        elif data[1] == ",":
                            if data[2] == " ":
                                if data[3] in ["'",'"']:
                                    translate_id = data[3:].split(data[3])[1]
                                    for char in ["%","+","(",")","-","?","."]:
                                        if char in translate_id:
                                            if (translate_id,dirpath+"/"+file) not in manuel_translate_ids:
                                                manuel_translate_ids.append((translate_id,dirpath+"/"+file))
                                            break
                                    else:
                                        if translate_id not in auto_translate_ids:
                                            auto_translate_ids.append(translate_id)
                                else:
                                    translate_id = data[3:].split(")")[0]
                                    if (translate_id,dirpath+"/"+file) not in manuel_translate_ids:
                                        manuel_translate_ids.append((translate_id,dirpath+"/"+file))
                    
                    # Splitting for translate
                    for data in file_content.split("translate(")[1:]:
                        if data[0] == "'":
                            separator = "'"
                        elif data[0] == '"':
                            separator = '"'
                        translate_id = data.split(")")[0]
                        if translate_id[0] == separator and translate_id[-1] == separator:
                            translate_id = translate_id[1:]
                            translate_id = translate_id[:-1]
                        else:
                            if (translate_id,dirpath+"/"+file) not in manuel_translate_ids:
                                manuel_translate_ids.append((translate_id,dirpath+"/"+file))
                            continue

                        for char in ["%","+","(",")","-","?","."]:
                            if char in translate_id:
                                if (translate_id,dirpath+"/"+file) not in manuel_translate_ids:
                                    manuel_translate_ids.append((translate_id,dirpath+"/"+file))
                                break
                        else:
                            if translate_id not in auto_translate_ids:
                                auto_translate_ids.append(translate_id)

    return auto_translate_ids,manuel_translate_ids

async def main():
    language_swap = {
            "cz":"cs",
            "de":"de",
            "en":"en",
            "es":"es",
            "fr":"fr",
            "it":"it",
            "nl":"nl",
            "pl":"pl",
            "ru":"ru",
            "sw":"sw"
    }
    auto,manual = scan_for_translate_ids()
    print("------------Bitte Manuell Prüfen---------------")
    for tid in manual:
        print(f"File: {tid[1].ljust(80," ")} |   ID: {tid[0]}")
    with open("tids.txt","w+") as file:
        for tid in auto[:-1]:
            file.write(tid+"\n")
        file.write(auto[-1])
    print("-----------------------------------------------")
    print(f"To ids to translate where added in <<< tids.txt >>> ({len(auto)} ids were found)")
    print("Please check and correct the translation ids then press ENTER.")
    input("Press [ENTER] to continue:")
    language_dict,full_language_dict = load_file_translations()
    with open("tids.txt","r+") as file:
        data = file.read(-1)
        file_data = data.split("\n")

    translator = googletrans.Translator()
    not_translated = []
    for language in language_dict.keys():
        with open(f"tids-{language}.txt","w+",encoding="utf-8") as file:
            for tid in file_data:
                if tid not in language_dict[language]:
                    translation = ""
                    if tid in full_language_dict["de"]:
                        print(f"Translating: {full_language_dict["de"][tid]["translation"]}| in language: {language}")
                        translation = await translator.translate(text=full_language_dict["de"][tid]["translation"],dest=language_swap[language],src="de")
                        translation = full_language_dict["de"][tid]["file"].ljust(30," ")+" | "+translation.text  
                    elif tid in full_language_dict["en"]:
                        print(f"Translating: {full_language_dict["en"][tid]["translation"]}| in language: {language}")
                        translation = await translator.translate(text=full_language_dict["en"][tid]["translation"],dest=language_swap[language],src="en")
                        translation = full_language_dict["en"][tid]["file"].ljust(30," ")+" | "+translation.text
                    if translation != "":
                        file.write(f"{tid.ljust(40," ")}| {translation}\n")
                    else:
                        not_translated.append(tid)
            
            if len(not_translated) != 0:
                file.write("\n")

            for tid in not_translated:
                file.write(f"{tid}\n")

    input("Press [ENTER] to apply the translations to their json files:")
    for language in language_dict.keys():
        with open(f"tids-{language}.txt","r+",encoding="utf-8") as file:
            data = file.readlines()
            for line in data:
                if line == "\n":
                    break
                line = line.split("| ")
                file = line[1].strip(" ")
                file = file[:-7] + language + file[ -5 :]
                tid = line[0].strip(" ")
                translation = line[2].strip(" ").replace("\n","")
                with open(os.path.join("phoscon_app","language",language,file),"r+",encoding="utf-8") as read_json:
                    json_data = json.load(read_json)
                    json_data[tid] = translation
                    with open(os.path.join("phoscon_app","language",language,file),"w+",encoding="utf-8") as write_json:
                        json.dump(json_data,write_json,indent=4,ensure_ascii=False)

if __name__ == "__main__":
    asyncio.run(main())