from tkinter import *
import re
import subprocess
import pyautogui

import UserData
import ResourceManager
import ProfileManager


def save_preferences():
  UserData.save_preferences({"server": server_address_field.get(), "username": username_field.get(), "windowed": windowed.get()})
  save_preferences_button.config(state=DISABLED, text="Saved!")
  root.after(5000, lambda: save_preferences_button.config(state=NORMAL, text="Save"))

def release_shift(is_windowed):
    if is_windowed:
        pyautogui.keyUp("shift")

def launch_exe():
    # Check for valid server address (Currently only supports numerical addresses (not domains.))
    if not validate_server_address(server_address_field.get()):
        print(f"Invalid address \"{server_address_field.get()}\", please use a proper one...")
        server_address_field.delete(0, END)
        server_address_field.insert(0, UserData.default_server_address)
        return

    # Validate username by checking if username length is reasonable.
    if not validate_username(username_field.get()):
        print(f"Username \"{username_field.get()}\" is too long, please use a shorter one...")
        username_field.delete(0, END)
        username_field.insert(0, UserData.default_username)
        return

    ProfileManager.change_username(username_field.get())

    # If game needs to be windowed then we use BF42Plus provided "workaround."
    if windowed.get():
        pyautogui.keyDown("shift")
    try:
        subprocess.call([
            "./BF1942.exe",
            "+game", "FinnWars",
            "+restart", "1",
            "+game", "FinnWars",
            "+joinServer", server_address_field.get()
        ])
        root.after(2000, lambda: release_shift(windowed.get()))
        root.after(2050, lambda: root.quit())
    except:
        launch_game.config(state=DISABLED, text=".exe not found!")
        root.after(5000, lambda: launch_game.config(state=NORMAL, text="Launch"))

    root.after(50, lambda: release_shift(windowed.get()))

def validate_server_address(server_address):
    ip_regex = r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$"
    try:
        if ":" in server_address:
            ip, port = server_address.split(":")
            if not re.match(ip_regex, ip):
                return False
            if not 1 <= int(port) <= 65535:
                return False
        else:
            if not re.match(ip_regex, server_address):
                return False
        return True
    except ValueError:
        return False

def validate_username(username):
    return len(username) <= 16

preferences = UserData.get_preferences()

# Create the main window
root = Tk()
root.title("FinnWarsLauncher | Koitelinkoski (v0.0.1)")
root.resizable(False, False)
#width = 720
#height = 360

scaling = 1
window_width = int(720*scaling)
window_height = int(360*scaling)
root.geometry(str(window_width) + "x" + str(window_height))

window_icon = ResourceManager.get_image_and_resize("assets/icon.png", 128, 128)
root.wm_iconphoto(False, window_icon)

background_image = ResourceManager.get_image_and_resize("assets/background.png", window_width, window_height)

background_label = Label(root, image=background_image)
background_label.pack(fill=BOTH, expand = YES)

# Create the text fields
font = ("arial", int(window_height/36))
box_width = int(window_width/24)

server_address_label = Label(root, text="Server Address:", font=font, fg="black", width=box_width)
server_address_field = Entry(root, font=font, width=box_width)
username_label = Label(root, text="Username:", font=font, fg="black", width=box_width)
username_field = Entry(root, font=font, width=box_width)
windowed = BooleanVar()
windowed.set(preferences["windowed"])
settings_label = Label(root, text="Settings", font=font, fg="black", width=int(window_width/11.3))
windowed_checkbutton = Checkbutton(root, text="Windowed", variable=windowed, font=font, width=int(window_width/26))

if "server" in preferences:
    server_address_field.insert(0, preferences["server"])
else:
    preferences["server"] = "23.88.63.235:14572"
    server_address_field.insert(0, "23.88.63.235:14572")
if "username" in preferences:
    username_field.insert(0, preferences["username"])
else:
    preferences["username"] = "FinnWarsLauncher"
    username_field.insert(0, "FinnWarsLauncher")

# Create the button and link it to the print_hello function
button_width = int(window_width/48)
save_preferences_button = Button(root, text="Save", command=save_preferences, width=button_width)
launch_game = Button(root, text="Launch", command=launch_exe, width=button_width)


# Place the widgets on the window
server_address_label.place(x=window_width/72, y=window_height/36)
server_address_field.place(x=window_width/72, y=int(window_height/7.2))
username_label.place(x=int(window_width/1.95), y=window_height/36)
username_field.place(x=int(window_width/1.95), y=int(window_height/7.2))

settings_label.place(x=int(window_width/72), y=int(window_height/3.2))
windowed_checkbutton.place(x=int(window_width/72), y=int(window_height/2.4))

save_preferences_button.place(x=int(window_width/2.4), y=int(window_height/1.16))
launch_game.place(x=int(window_width/1.4), y=int(window_height/1.16))

# Start the main event loop
root.mainloop()
