from tkinter import *
from PIL import ImageTk, Image
import time
import re
import userdata
import asyncio
import subprocess
import os
import sys

def resource_path(relative_path):
    base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))
    return os.path.join(base_path, relative_path)

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

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("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

    if not validate_username(username_field.get()):
        print("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

    print("IP Address: " + server_address_field.get())
    print("Username: " + username_field.get())
    subprocess.call(
        ["./Battlefield 1942/Battlefield 1942/BF1942.exe","+game","FinnWars","+restart","1","+game","FinnWars","+joinServer",server_address_field.get()]
    )
    root.quit

def validate_server_address(server_address):
    ip_regex = r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$"
    port_regex = r"^\d+$"


    try:
        if ":" in server_address:
            ip, port = server_address.split(":")

            if not re.match(ip_regex, ip):
                return False

            port = int(port)
            if port < 1 or port > 65535:
                return False
        else:
            ip = server_address
            if not re.match(ip_regex, ip):
                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))

# Background image scaled correctly
image = Image.open(resource_path("assets/background.png"))
resized_image = image.resize((window_width, window_height))
photo = ImageTk.PhotoImage(resized_image)

background_label = Label(root, image=photo)
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)

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)

menu_bar = Menu(root)
root.config(menu=menu_bar)

file_menu = Menu(root, tearoff=0)
file_menu.add_command(label="Settings")
file_menu.add_command(label="Exit", command=root.quit)
menu_bar.add_cascade(label="File", menu=file_menu)

# 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))
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))

#server_address_label.place(x=10, y=20)
#server_address_field.place(x=10, y=50)
#username_label.place(x=370, y=20)
#username_field.place(x=370, y=50)
#save_preferences_button.place(x=300, y=310)
#launch_game.place(x=510, y=310)

# Start the main event loop
root.mainloop()
