import tkinter as tk
from tkinter import filedialog, ttk, messagebox
import nltk
from nltk.sentiment.vader import SentimentIntensityAnalyzer
import os
import pandas as pd
from openpyxl import load_workbook
from openpyxl.styles import PatternFill
from openpyxl.chart import PieChart, Reference
from openpyxl.chart.label import DataLabelList

class SentimentAnalyzerApp:
    def __init__(self, root):
        self.root = root
        self.root.title("Sentiment Analyzer")
        self.root.geometry("600x400")

        # Verificare VADER
        try:
            nltk.data.find('vader_lexicon')
        except LookupError:
            nltk.download('vader_lexicon')

        ttk.Label(root, text="Select text files to analyze:").pack(pady=10)
        ttk.Button(root, text="Select Files", command=self.select_files).pack(pady=5)
        
        self.progress_text = tk.Text(root, height=15, width=70)
        self.progress_text.pack(pady=10)
        
        self.analyze_btn = ttk.Button(root, text="Start Analysis", command=self.start_analysis)
        self.analyze_btn.pack(pady=5)
        self.analyze_btn.config(state='disabled')

        self.selected_files = []

    def select_files(self):
        self.selected_files = filedialog.askopenfilenames(
            title="Select Text Files",
            filetypes=[("Text files", "*.txt")],
            multiple=True
        )
        if self.selected_files:
            self.progress_text.delete(1.0, tk.END)
            self.progress_text.insert(tk.END, f"Selected {len(self.selected_files)} files:\n")
            for file in self.selected_files:
                self.progress_text.insert(tk.END, f"{os.path.basename(file)}\n")
            self.analyze_btn.config(state='normal')

    def process_file(self, file_path):
        sid = SentimentIntensityAnalyzer()
        try:
            with open(file_path, "r", encoding='utf-8') as f:
                text = f.read()
            scores = sid.polarity_scores(text)
            dominant = max(scores['neg'], scores['neu'], scores['pos'])
            if dominant == scores['neg']:
                dominant_sentiment = 'Negative'
            elif dominant == scores['pos']:
                dominant_sentiment = 'Positive'
            else:
                dominant_sentiment = 'Neutral'
            file_name = os.path.basename(file_path)
            return [file_name, scores['neg'], scores['neu'], scores['pos'], scores['compound'], dominant_sentiment]
        except Exception as e:
            self.progress_text.insert(tk.END, f"Error processing {file_path}: {str(e)}\n")
            file_name = os.path.basename(file_path)
            return [file_name, 0.0, 0.0, 0.0, 0.0, 'Error']

    def start_analysis(self):
        if not self.selected_files:
            return

        self.progress_text.insert(tk.END, "Starting analysis...\n")
        self.root.update()

        results = []
        for file in self.selected_files:
            result = self.process_file(file)
            results.append(result)
            self.progress_text.insert(tk.END, f"Processed: {os.path.basename(file)}\n")
            self.root.update()

        # Creare DataFrame
        df = pd.DataFrame(results, columns=['File', 'Negative', 'Neutral', 'Positive', 'Compound', 'Dominant'])
        
        # Salvare în Excel
        excel_file_path = f"results_{pd.Timestamp.now().strftime('%Y%m%d_%H%M%S')}.xlsx"
        df.to_excel(excel_file_path, index=False)

        # Formatare Excel
        wb = load_workbook(excel_file_path)
        ws = wb.active
        
        # Definire culori
        red_fill = PatternFill(start_color='FF9999', end_color='FF9999', fill_type='solid')    # Negative
        yellow_fill = PatternFill(start_color='FFFF99', end_color='FFFF99', fill_type='solid')  # Neutral
        green_fill = PatternFill(start_color='99FF99', end_color='99FF99', fill_type='solid')   # Positive
        
        # Aplicare culori pe coloanele de sentiment
        for row in range(2, len(results) + 2):
            neg_cell = f'B{row}'  # Negative
            neu_cell = f'C{row}'  # Neutral
            pos_cell = f'D{row}'  # Positive
            dom_cell = f'F{row}'  # Dominant
            
            neg_val = float(ws[neg_cell].value)
            neu_val = float(ws[neu_cell].value)
            pos_val = float(ws[pos_cell].value)
            
            if neg_val > neu_val and neg_val > pos_val:
                ws[neg_cell].fill = red_fill
            elif neu_val > neg_val and neu_val > pos_val:
                ws[neu_cell].fill = yellow_fill
            elif pos_val > neg_val and pos_val > neu_val:
                ws[pos_cell].fill = green_fill
            
            dominant_value = ws[dom_cell].value
            if dominant_value == 'Negative':
                ws[dom_cell].fill = red_fill
            elif dominant_value == 'Positive':
                ws[dom_cell].fill = green_fill
            elif dominant_value == 'Neutral':
                ws[dom_cell].fill = yellow_fill

        # Ajustare lățime coloane
        for col in ws.columns:
            max_length = 0
            column = col[0].column_letter
            for cell in col:
                try:
                    if len(str(cell.value)) > max_length:
                        max_length = len(str(cell.value))
                except:
                    pass
            adjusted_width = (max_length + 2)
            ws.column_dimensions[column].width = adjusted_width

        # Adăugare grafic pie în aceeași foaie
        sentiment_counts = df['Dominant'].value_counts()
        if not sentiment_counts.empty:
            # Adăugăm datele pentru grafic sub tabelul principal
            start_row = len(results) + 3  # Lăsăm o linie liberă după tabel
            ws[f'A{start_row}'] = 'Sentiment'
            ws[f'B{start_row}'] = 'Count'
            for i, (sentiment, count) in enumerate(sentiment_counts.items(), start=start_row + 1):
                ws[f'A{i}'] = sentiment
                ws[f'B{i}'] = count

            pie = PieChart()
            pie.title = "Sentiment Distribution"
            labels = Reference(ws, min_col=1, min_row=start_row + 1, max_row=start_row + len(sentiment_counts))
            data = Reference(ws, min_col=2, min_row=start_row, max_row=start_row + len(sentiment_counts))
            pie.add_data(data, titles_from_data=True)
            pie.set_categories(labels)
            pie.dataLabels = DataLabelList()  # Creăm explicit obiectul DataLabelList
            pie.dataLabels.showPercent = True  # Afișăm procentele
            
            # Poziționăm graficul sub date
            ws.add_chart(pie, f"H{start_row}")
            wb.save(excel_file_path)
        else:
            self.progress_text.insert(tk.END, "No valid sentiment data for chart!\n")
            wb.save(excel_file_path)

        # Afișare statistici
        self.progress_text.insert(tk.END, "\nStatistics:\n" + df.describe().to_string() + "\n")
        self.progress_text.insert(tk.END, f"Results saved to: {excel_file_path}\n")
        messagebox.showinfo("Success", "Analysis completed with chart!")

def main():
    root = tk.Tk()
    app = SentimentAnalyzerApp(root)
    root.mainloop()

if __name__ == "__main__":
    main()
