import tkinter as tk
from tkinter import filedialog, ttk
import pandas as pd
from pathlib import Path
import webbrowser

class ExcelMerger:
    def __init__(self, root):
        self.root = root
        self.root.title("Excel Birleştirici")
        
        # Pencere boyutunu sabitle
        self.root.resizable(False, False)
        
        # Pencere boyutunu ayarla
        window_width = 500
        window_height = 400
        screen_width = root.winfo_screenwidth()
        screen_height = root.winfo_screenheight()
        center_x = int(screen_width/2 - window_width/2)
        center_y = int(screen_height/2 - window_height/2)
        self.root.geometry(f'{window_width}x{window_height}+{center_x}+{center_y}')
        
        self.files = []
        
        # Ana container
        self.main_frame = ttk.Frame(root)
        self.main_frame.pack(padx=10, pady=10, fill=tk.BOTH, expand=True)
        
        # Başlık
        title_label = ttk.Label(self.main_frame, text="Excel Dosyası Birleştirici", font=('Helvetica', 14, 'bold'))
        title_label.pack(pady=10)
        
        # Dosya listesi
        self.file_frame = ttk.Frame(self.main_frame)
        self.file_frame.pack(fill=tk.BOTH, expand=True, pady=5)
        
        self.file_listbox = tk.Listbox(self.file_frame, width=50, height=10)
        self.file_listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        
        # Kaydırma çubuğu
        scrollbar = ttk.Scrollbar(self.file_frame, orient="vertical", command=self.file_listbox.yview)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        self.file_listbox.configure(yscrollcommand=scrollbar.set)
        
        # Buton container
        button_frame = ttk.Frame(self.main_frame)
        button_frame.pack(pady=10)
        
        # Butonlar
        ttk.Button(button_frame, text="Dosya Ekle", command=self.add_files).pack(side=tk.LEFT, padx=5)
        ttk.Button(button_frame, text="Seçili Dosyayı Kaldır", command=self.remove_file).pack(side=tk.LEFT, padx=5)
        ttk.Button(button_frame, text="Birleştir", command=self.merge_files).pack(side=tk.LEFT, padx=5)
        
        # Alt bilgi container
        footer_frame = ttk.Frame(self.main_frame)
        footer_frame.pack(side=tk.BOTTOM, pady=10)
        
        # Hakkında butonu
        ttk.Button(footer_frame, text="Hakkında", command=self.open_about).pack(side=tk.BOTTOM)
        
        # Durum etiketi
        self.status_label = ttk.Label(self.main_frame, text="")
        self.status_label.pack(pady=5)

    def add_files(self):
        files = filedialog.askopenfilenames(
            title="Excel Dosyalarını Seç",
            filetypes=[("Excel files", "*.xlsx *.xls")]
        )
        for file in files:
            if file not in self.files:
                self.files.append(file)
                self.file_listbox.insert(tk.END, Path(file).name)
    
    def remove_file(self):
        selection = self.file_listbox.curselection()
        if selection:
            index = selection[0]
            self.file_listbox.delete(index)
            self.files.pop(index)
    
    def merge_files(self):
        if not self.files:
            self.status_label.config(text="Lütfen en az bir dosya ekleyin!")
            return
            
        try:
            # Final DataFrame'i oluştur
            final_df = pd.DataFrame()
            
            # Her dosyayı sırayla işle
            for i, file in enumerate(self.files):
                # Dosyayı oku
                df = pd.read_excel(file)
                
                # İlk dosya değilse boş satır ekle
                if i > 0:
                    empty_row = pd.DataFrame([[None] * len(df.columns)], columns=df.columns)
                    final_df = pd.concat([final_df, empty_row], ignore_index=True)
                
                # Verileri ekle
                final_df = pd.concat([final_df, df], ignore_index=True)
            
            # Kaydetme dialog'unu aç
            save_path = filedialog.asksaveasfilename(
                defaultextension=".xlsx",
                filetypes=[("Excel files", "*.xlsx")],
                title="Birleştirilmiş Dosyayı Kaydet"
            )
            
            if save_path:
                # Excel yazıcısını oluştur
                with pd.ExcelWriter(save_path, engine='openpyxl') as writer:
                    final_df.to_excel(writer, index=False, sheet_name='Birleştirilmiş')
                
                self.status_label.config(text=f"Dosyalar başarıyla birleştirildi!\nKaydedilen: {Path(save_path).name}")
            
        except Exception as e:
            self.status_label.config(text=f"Hata oluştu: {str(e)}")
    
    def open_about(self):
        webbrowser.open('https://ettunc.com')

if __name__ == "__main__":
    root = tk.Tk()
    app = ExcelMerger(root)
    root.mainloop()
