import tkinter as tk
from tkinter import filedialog, messagebox
import zipfile
import os
import shutil
import webbrowser

class KMZCompressorApp:
    def __init__(self, root):
        self.root = root
        self.root.title("KMZ/KML Dosyası Boyut Küçültme")
        self.root.geometry("400x300")
        self.root.resizable(False, False)  # Disable resizing

        self.label = tk.Label(root, text="KMZ veya KML dosyasını seçin:")
        self.label.pack(pady=10)

        self.select_button = tk.Button(root, text="Dosya Seç", command=self.select_file)
        self.select_button.pack(pady=5)

        self.compress_button = tk.Button(root, text="Boyut Küçült", command=self.compress_file, state=tk.DISABLED)
        self.compress_button.pack(pady=5)

        self.old_size_label = tk.Label(root, text="")
        self.old_size_label.pack(pady=5)

        self.new_size_label = tk.Label(root, text="")
        self.new_size_label.pack(pady=5)

        self.ratio_label = tk.Label(root, text="")
        self.ratio_label.pack(pady=5)

        self.about_button = tk.Button(root, text="Hakkında", command=self.open_about)
        self.about_button.pack(pady=5)

        self.file_path = ""

    def select_file(self):
        self.file_path = filedialog.askopenfilename(filetypes=[("KMZ or KML Files", "*.kmz *.kml")])
        if self.file_path:
            self.compress_button.config(state=tk.NORMAL)
            self.old_size_label.config(text=f"Eski Boyut: {os.path.getsize(self.file_path) / 1024:.2f} KB")

    def compress_file(self):
        if not self.file_path:
            messagebox.showerror("Hata", "Lütfen bir KMZ veya KML dosyası seçin.")
            return

        temp_dir = "temp_kmz"

        # Create temp directory
        if os.path.exists(temp_dir):
            shutil.rmtree(temp_dir)
        os.makedirs(temp_dir)

        file_extension = os.path.splitext(self.file_path)[1].lower()

        if file_extension == ".kmz":
            with zipfile.ZipFile(self.file_path, 'r') as kmz:
                kmz.extractall(temp_dir)
            kml_file = None
            for root, dirs, files in os.walk(temp_dir):
                for file in files:
                    if file.endswith(".kml"):
                        kml_file = os.path.join(root, file)
                        break

        elif file_extension == ".kml":
            shutil.copy(self.file_path, os.path.join(temp_dir, "doc.kml"))
            kml_file = os.path.join(temp_dir, "doc.kml")

        if kml_file:
            self.optimize_kml(kml_file)

        new_kmz_path = filedialog.asksaveasfilename(defaultextension=".kmz", filetypes=[("KMZ Files", "*.kmz")])
        if new_kmz_path:
            with zipfile.ZipFile(new_kmz_path, 'w', zipfile.ZIP_DEFLATED) as kmz:
                for root, dirs, files in os.walk(temp_dir):
                    for file in files:
                        kmz.write(os.path.join(root, file), os.path.relpath(os.path.join(root, file), temp_dir))

            new_size = os.path.getsize(new_kmz_path) / 1024
            self.new_size_label.config(text=f"Yeni Boyut: {new_size:.2f} KB")

            old_size = os.path.getsize(self.file_path) / 1024
            compression_ratio = (old_size - new_size) / old_size * 100
            self.ratio_label.config(text=f"Sıkıştırma Oranı: {compression_ratio:.2f}%")

            messagebox.showinfo("Başarılı", "KMZ dosyası başarıyla küçültüldü.")
        else:
            messagebox.showwarning("İptal", "Kaydetme işlemi iptal edildi.")

        # Clean up temp directory
        shutil.rmtree(temp_dir)

    def optimize_kml(self, kml_path):
        # Read the KML file content
        with open(kml_path, 'r', encoding='utf-8') as file:
            kml_content = file.read()

        # Optimize the KML content
        optimized_kml_content = self.remove_unnecessary_data(kml_content)

        # Write the optimized content back to the KML file
        with open(kml_path, 'w', encoding='utf-8') as file:
            file.write(optimized_kml_content)

    def remove_unnecessary_data(self, kml_content):
        # Here you can add code to remove unnecessary data from the KML content.
        # For example, you can remove comments, whitespace, or reduce the precision of coordinates.
        import re

        # Remove comments
        kml_content = re.sub(r'<!--.*?-->', '', kml_content, flags=re.DOTALL)

        # Remove extra whitespace
        kml_content = re.sub(r'\s+', ' ', kml_content)

        # Optionally, reduce the precision of coordinates (example: 6 decimal places)
        kml_content = re.sub(r'(\d+\.\d{6})\d+', r'\1', kml_content)

        return kml_content

    def open_about(self):
        webbrowser.open("https://ettunc.com")

if __name__ == "__main__":
    root = tk.Tk()
    app = KMZCompressorApp(root)
    root.mainloop()
