from shutil import copy2
import tkinter as tk
import os
import sys
from tkinter import filedialog
from tkinter import messagebox
from tkinter import simpledialog
from PIL import Image, ImageTk
from pydub import AudioSegment
from locale import getdefaultlocale
from lang import lang
defaultlang, encoding = getdefaultlocale()

root = tk.Tk()
root.title("Funkalot Asset Generator")
root.configure(bg="black")
root.iconphoto(True, tk.PhotoImage(file="resources/icon.png"))
root.geometry("700x550")
canvas = tk.Canvas(root, highlightthickness=0, bg = 'black', height = 250, width = 500)
canvas.pack()
pil_image = Image.open("resources/logo.png")
tk_image = ImageTk.PhotoImage(pil_image)
logo = canvas.create_image(250,-120, anchor = tk.N, image = tk_image)

def create_command():
    if getattr(sys, 'frozen', False):
        exec_dir = os.path.dirname(sys.executable)
    else:
        exec_dir = os.path.dirname(os.path.abspath(__file__))
    while True:
        if os.path.exists(exec_dir+"\\ffmpeg\\ffmpeg.exe") == False:
            messagebox.showinfo(lang("info", defaultlang), lang("noffmpeg", defaultlang))
            mp3_path = filedialog.askopenfilename(
            title=lang("choosemusicfile", defaultlang),
            initialdir="/",
            filetypes=[(lang("oggfiles", defaultlang), "*.ogg"), (lang("allfiles", defaultlang), "*.*")]
            )
            if mp3_path == "":
                messagebox.showerror(lang("error", defaultlang), lang("missingpatherror", defaultlang))
                return 0
            if mp3_path[-3:-1]+mp3_path[-1] == "ogg": break
            messagebox.showerror(lang("error", defaultlang), lang("unsupportederror", defaultlang)+f"{mp3_path}")
            continue
        mp3_path = filedialog.askopenfilename(
            title=lang("choosemusicfile", defaultlang),
            initialdir="/",
            filetypes=[(lang("mp3files", defaultlang), "*.mp3"), (lang("oggfiles", defaultlang), "*.ogg"), (lang("allfiles", defaultlang), "*.*")]
            )
        if mp3_path == "":
            messagebox.showerror(lang("error", defaultlang), lang("missingpatherror", defaultlang))
            return 0
        if ((mp3_path[-3:-1]+mp3_path[-1] == "mp3") or (mp3_path[-3:-1]+mp3_path[-1] == "ogg")): break
        messagebox.showerror(lang("error", defaultlang), lang("unsupportederror", defaultlang)+f"{mp3_path}")

    while True:
        png_path = filedialog.askopenfilename(
            title=lang("chooseimagefile", defaultlang),
            initialdir="/",
            filetypes=[(lang("pngfiles", defaultlang), "*.png"), (lang("allfiles", defaultlang), "*.*")]
            )
        if png_path == "":
            messagebox.showerror(lang("error", defaultlang), lang("missingpatherror", defaultlang))
            return 0
        if png_path[-3:-1]+png_path[-1] == "png": break
        messagebox.showerror(lang("error", defaultlang), lang("unsupportederror", defaultlang)+f"{png_path}")

    while True:    
        namespace = simpledialog.askstring(lang("input",defaultlang), lang("namespace",defaultlang))
        if namespace == "":
            messagebox.showerror(lang("error", defaultlang), lang("noinput", defaultlang))
            return 0
        namespace = namespace.lower()
        if ((namespace.isalnum() and (namespace.isascii())) == False) or namespace == "minecraft":
            messagebox.showerror(lang("error", defaultlang), lang("badinput", defaultlang))
            continue
        break
    
    while True:
        name = simpledialog.askstring(lang("input",defaultlang), lang("name",defaultlang))
        if name == "":
            messagebox.showerror(lang("error", defaultlang), lang("noinput", defaultlang))
            return 0
        name = name.lower()
        if (name.isalnum() and name.isascii()) == False:
            messagebox.showerror(lang("error", defaultlang), lang("badinput", defaultlang))
            continue
        if name == "gaster":
            root.destroy()
            return 0
        break
    
    directory = f"generated\\Funkalot Level {namespace}.{name}\\assets\\{namespace}\\sounds\\music"
    directory = os.path.join(exec_dir, directory)
    os.makedirs(directory,exist_ok=True)
    if (mp3_path[-3:-1]+mp3_path[-1] == "mp3"):
        open(f"{directory.replace("\\","/")}/{name}.ogg", "wb")
        AudioSegment.converter=exec_dir+"\\ffmpeg\\ffmpeg.exe"
        sound = AudioSegment.from_mp3(mp3_path)
        sound.export(directory.replace("\\","/")+f"/{name}.ogg", format="ogg")
    else:
        open(f"{directory.replace("\\","/")}/{name}.ogg", "wb")
        copy2(mp3_path,f"{directory}\\{name}.ogg")
    with open(f"{exec_dir}\\generated\\Funkalot Level {namespace}.{name}\\assets\\{namespace}\\sounds.json", "w") as soundsjsonfile:
        soundsjsonfile.write(f"{{\"music.{name}\":{{\"category\": \"master\",\"sounds\": [{{\"name\": \"{namespace}:music/{name}\", \"stream\": true, \"preload\": true}}]}}}}")

    directory = f"generated\\Funkalot Level {namespace}.{name}\\assets\\{namespace}\\models\\cover"
    os.makedirs(f"{exec_dir}\\{directory}",exist_ok=True)
    with open(f"{exec_dir}\\{directory}\\{name}.json", "w") as modeljson:
        modeljson.write(f"{{\"parent\": \"funkalot:cover/base\",\"textures\": {{\"0\": \"{namespace}:item/cover/{name}\"}}}}")

    directory = f"generated\\Funkalot Level {namespace}.{name}\\assets\\{namespace}\\items\\cover"
    os.makedirs(f"{exec_dir}\\{directory}",exist_ok=True)
    with open(f"{exec_dir}\\{directory}\\{name}.json", "w") as itemjson:
        itemjson.write(f"{{\"model\": {{\"type\": \"minecraft:model\",\"model\": \"{namespace}:cover/{name}\"}}}}")

    directory = f"generated\\Funkalot Level {namespace}.{name}\\assets\\{namespace}\\textures\\item\\cover"
    directory = os.path.join(exec_dir, directory)
    os.makedirs(directory,exist_ok=True)
    copy2(png_path,f"{directory}\\{name}.png")

    directory = f"generated\\Funkalot Level {namespace}.{name}"
    directory = os.path.join(exec_dir, directory)
    copy2(png_path,f"{directory}\\pack.png")
    with open(f"{directory}\\pack.mcmeta", "w", encoding='utf-8') as mcmeta:
        mcmeta.write(f"{{\"pack\": {{\"pack_format\": 64,\"description\": \"{lang("mcmeta",defaultlang)}\"}}}}")

    messagebox.showinfo(lang("info", defaultlang), lang("success", defaultlang))
    os.startfile(exec_dir+"\\generated")
    
    
def info_command():
    messagebox.showinfo(lang("info", defaultlang), lang("infobody", defaultlang))

label = tk.Label(root, text=lang("body", defaultlang), bg="black", fg="white", font=("Arial", 15))
label.pack()
create = tk.Button(root, text=lang("create", defaultlang), highlightthickness=0, bg="white", fg="black", activebackground="gray", command=create_command)
create.pack()
label = tk.Label(root, text=lang("body", defaultlang), bg="black", fg="black", font=("Arial", 2))
label.pack()
info = tk.Button(root, text=lang("info", defaultlang), highlightthickness=0, bg="white", fg="black", activebackground="gray", command=info_command)
info.pack()


root.mainloop()
