import tkinter as tk
from tkinter import filedialog, messagebox
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import os

class CycleCapacityPlotApp:
    def __init__(self, root):
        self.root = root
        self.root.title("Cycle Life Plotter (Thesis Style)")
        self.root.geometry("450x250")

        # Instructions
        self.label = tk.Label(root, text="Select Excel files for Cycle Life Test\n(Matches Thesis Font Format)", font=("Arial", 10))
        self.label.pack(pady=20)

        # Buttons
        self.select_button = tk.Button(root, text="Select Files & Plot", command=self.select_files, bg="#e1e1e1", height=2)
        self.select_button.pack(pady=5, fill='x', padx=50)

        self.quit_button = tk.Button(root, text="Quit", command=root.quit)
        self.quit_button.pack(pady=5)

    def setup_thesis_style(self):
        """Configures matplotlib to match the Rate Capability thesis style."""
        plt.rcParams.update({
            'font.family': 'serif',          # MATCHED: Serif font (Times-like)
            'font.size': 12,
            'axes.labelsize': 14,
            'axes.titlesize': 16,
            'xtick.labelsize': 12,
            'ytick.labelsize': 12,
            'figure.dpi': 150,               # High DPI for display
            'savefig.dpi': 300,              # High DPI for saving
            'lines.linewidth': 1.5,
            'axes.grid': True,
            'grid.alpha': 0.3,               # MATCHED: Subtle grid
            'legend.fontsize': 10,
            'legend.frameon': True,
            'legend.edgecolor': 'black',     # MATCHED: Sharp border
            'legend.fancybox': False         # MATCHED: Square corners
        })

    def select_files(self):
        file_paths = filedialog.askopenfilenames(
            title="Select Excel Files",
            filetypes=[("Excel Files", "*.xlsx")]
        )
        if file_paths:
            self.plot_files(file_paths)

    def plot_files(self, file_paths):
        # Apply the matching thesis style
        self.setup_thesis_style()
        
        # Standardize size to match your other figure (8x5)
        fig, ax = plt.subplots(figsize=(8, 5))

        # Use the same color palette
        colors = list(mcolors.TABLEAU_COLORS.values())
        
        files_plotted = 0

        for i, file_path in enumerate(file_paths):
            try:
                xls = pd.ExcelFile(file_path)
                if 'cycle' not in xls.sheet_names:
                    print(f"Skipping {os.path.basename(file_path)}: No 'cycle' sheet.")
                    continue

                df = pd.read_excel(xls, sheet_name='cycle')
                
                req_cols = ['Cycle Index', 'DChg. Spec. Cap.(mAh/g)']
                if all(col in df.columns for col in req_cols):
                    cycle_index = df['Cycle Index']
                    discharge_capacity = df['DChg. Spec. Cap.(mAh/g)']

                    label = os.path.splitext(os.path.basename(file_path))[0]
                    color = colors[i % len(colors)]
                    
                    # NOTE: For long cycle life (e.g., 3000 cycles), we usually stick to lines 
                    # instead of markers to prevent the graph from becoming a solid blob.
                    ax.plot(cycle_index, discharge_capacity, label=label, color=color, linewidth=1.5)
                    files_plotted += 1
                else:
                    print(f"Skipping {os.path.basename(file_path)}: Columns missing.")

            except Exception as e:
                messagebox.showwarning("File Error", f"Error with file '{os.path.basename(file_path)}': {str(e)}")

        if files_plotted == 0:
            messagebox.showinfo("No Data", "No valid data found to plot.")
            return

        # --- Thesis Styling Applied ---
        # Updated Title to match the requested format context
        ax.set_title('Cycle Test @ 4A/g: Specific Discharge Capacity vs Cycle Index', pad=15)
        ax.set_xlabel('Cycle Index')
        ax.set_ylabel('Discharge Specific Capacity (mAh/g)')
        
        # Limits (Optional: Adjust based on your data)
      
        ax.set_xlim(left=0) 
        ax.set_ylim(0, 300)
        # ax.set_ylim(bottom=80) 

        # Grid
        ax.grid(True, which='major', linestyle='-', linewidth=0.75, color='black', alpha=0.3)
        ax.minorticks_on()
        ax.grid(True, which='minor', linestyle=':', linewidth=0.5, color='gray', alpha=0.3)

        # Legend (Top Right is standard for Cycle Life as curves drop)
        ax.legend(loc='upper right', frameon=True, edgecolor='black', fancybox=False)
        
        plt.tight_layout()
        plt.show()

if __name__ == '__main__':
    root = tk.Tk()
    app = CycleCapacityPlotApp(root)
    root.mainloop()