import tkinter as tk
from tkinter import filedialog, messagebox
import re

class HammerMapEditor:
    def __init__(self, root):
        self.root = root
        self.root.title("Hammer Map Notepad")
        self.root.geometry("800x600")
        
        # Default color scheme (Light mode)
        self.is_dark_mode = False
        self.bg_color = "#FFFFFF"
        self.fg_color = "#000000"
        self.highlight_color = "#A5A5A5"
        self.comment_color = "#228B22"
        
        # Create the Text widget for the editor area
        self.text_area = tk.Text(self.root, wrap=tk.WORD, undo=True, font=("Courier", 12))
        self.text_area.pack(expand=True, fill=tk.BOTH)
        
        # Apply initial color scheme
        self.apply_color_scheme()
        
        # Create a Menu bar
        self.menu_bar = tk.Menu(self.root)
        self.root.config(menu=self.menu_bar)
        
        # File menu
        self.file_menu = tk.Menu(self.menu_bar, tearoff=0)
        self.menu_bar.add_cascade(label="File", menu=self.file_menu)
        self.file_menu.add_command(label="Open", command=self.open_file)
        self.file_menu.add_command(label="Save", command=self.save_file)
        self.file_menu.add_command(label="Exit", command=self.exit_app)
        
        # Edit menu
        self.edit_menu = tk.Menu(self.menu_bar, tearoff=0)
        self.menu_bar.add_cascade(label="Edit", menu=self.edit_menu)
        self.edit_menu.add_command(label="Undo", command=self.text_area.edit_undo)
        self.edit_menu.add_command(label="Redo", command=self.text_area.edit_redo)
        
        # View menu (for dark/light mode toggle)
        self.view_menu = tk.Menu(self.menu_bar, tearoff=0)
        self.menu_bar.add_cascade(label="View", menu=self.view_menu)
        self.view_menu.add_command(label="Toggle Dark/Light Mode", command=self.toggle_mode)
        
        self.current_file = None

    def apply_color_scheme(self):
        """Apply colors based on the selected mode (dark or light)."""
        self.text_area.config(bg=self.bg_color, fg=self.fg_color)
        self.root.config(bg=self.bg_color)
        
        # Clear and reapply the color scheme to the entire text area
        self.highlight_syntax()
        
    def toggle_mode(self):
        """Switch between dark and light mode."""
        if self.is_dark_mode:
            # Switch to light mode
            self.bg_color = "#FFFFFF"
            self.fg_color = "#000000"
            self.highlight_color = "#A5A5A5"
            self.comment_color = "#228B22"
        else:
            # Switch to dark mode
            self.bg_color = "#2E2E2E"
            self.fg_color = "#DCDCDC"
            self.highlight_color = "#A5A5A5"
            self.comment_color = "#98FB98"
        
        self.is_dark_mode = not self.is_dark_mode
        self.apply_color_scheme()

    def open_file(self):
        file_path = filedialog.askopenfilename(
            filetypes=[("Valve Map Files", "*.vmf"), ("All Files", "*.*")]
        )
        if file_path:
            try:
                with open(file_path, 'r', encoding='utf-8') as file:
                    content = file.read()
                    self.text_area.delete(1.0, tk.END)
                    self.text_area.insert(tk.END, content)
                    self.current_file = file_path
                    self.highlight_syntax()  # Highlight syntax after loading the file
            except Exception as e:
                messagebox.showerror("Error", f"Failed to open file: {e}")

    def save_file(self):
        if self.current_file:
            self._save_existing_file(self.current_file)
        else:
            self.save_as_file()

    def save_as_file(self):
        file_path = filedialog.asksaveasfilename(
            defaultextension=".vmf",
            filetypes=[("Valve Map Files", "*.vmf"), ("All Files", "*.*")]
        )
        if file_path:
            self._save_existing_file(file_path)

    def _save_existing_file(self, file_path):
        try:
            with open(file_path, 'w', encoding='utf-8') as file:
                content = self.text_area.get(1.0, tk.END)
                file.write(content.strip())  # Remove any extra newlines
                self.current_file = file_path
                messagebox.showinfo("Saved", f"File saved successfully: {file_path}")
        except Exception as e:
            messagebox.showerror("Error", f"Failed to save file: {e}")
    
    def exit_app(self):
        if messagebox.askokcancel("Quit", "Do you want to quit without saving?"):
            self.root.quit()

    def highlight_syntax(self):
        """Apply basic syntax highlighting for the .vmf format."""
        content = self.text_area.get(1.0, tk.END)
        
        # Find and highlight comments
        self.apply_syntax_color(r"//.*", self.comment_color)  # Comment lines start with //
        
        # Find and highlight key Valve Map Functions (like "worldspawn")
        self.apply_syntax_color(r"\b(worldspawn|entity|solid|brush|vertex|material|texture)\b", self.highlight_color)
    
    def apply_syntax_color(self, pattern, color):
        """Apply a color to the matching text."""
        self.text_area.tag_remove("highlight", 1.0, tk.END)  # Clear previous highlights
        start = 1.0
        while True:
            start = self.text_area.search(pattern, start, stopindex=tk.END, regexp=True)
            if not start:
                break
            end = f"{start}+{len(self.text_area.get(start, start + '+1c'))}c"
            self.text_area.tag_add("highlight", start, end)
            self.text_area.tag_configure("highlight", foreground=color)
            start = end

# Create the main window
root = tk.Tk()
app = HammerMapEditor(root)

# Start the Tkinter event loop
root.mainloop()