import re
from google.oauth2 import service_account
from googleapiclient.discovery import build
from datetime import datetime, timedelta
import collections
from get_calendar_service import get_calendar_service
import seaborn as sns
import matplotlib.pyplot as plt


def clean_name(name):
    name = re.sub(r"[^\w\s]", "", name)  # Remove all non-word characters
    name = re.sub(r"\s+", " ",
                  name)  # Replace multiple spaces with a single space
    name = name.lower().strip(
    )  # Convert to lower case and strip leading and trailing spaces
    return name


def list_calendar_data(service, calendar_id):
    time_min = datetime.utcnow().replace(
        month=1, day=1, hour=0, minute=0,
        second=0).isoformat() + "Z"  # Start of this year
    time_max = datetime.utcnow().replace(
        month=12, day=31, hour=23, minute=59,
        second=59).isoformat() + "Z"  # End of this year

    # Fetch events
    events_result = service.events().list(calendarId=calendar_id,
                                          timeMin=time_min,
                                          timeMax=time_max,
                                          singleEvents=True,
                                          orderBy="startTime").execute()
    events = events_result.get("items", [])

    # Initialize a counter to keep track of days off for each worker
    days_off_counter = collections.defaultdict(
        float)  # Changed to float for half days

    # Process each event
    for event in events:
        start = event["start"].get("dateTime", event["start"].get("date"))
        end = event["end"].get("dateTime", event["end"].get("date"))
        start_date = datetime.fromisoformat(
            start) if "T" in start else datetime.strptime(start, "%Y-%m-%d")
        end_date = datetime.fromisoformat(
            end) if "T" in end else datetime.strptime(end, "%Y-%m-%d")

        days_off = (end_date - start_date).days
        title = event["summary"].lower()

        # Handle "fél nap" and other special cases
        if "fél nap" in title:
            days_off = 0.5
        title = re.sub(r"fél nap|beteg|-", "",
                       title)  # Remove specific words and characters
        title = clean_name(title)

        # Identify worker name
        synonyms = {"szabi": "", "szabadság": "", "szabin": ""}
        name_synonyms = {
            "ági n": "ági",
            "ági": "ági",
            "gyetván zoli": "zoli",
            "zoli": "zoli"
        }

        for keyword in ["szabi", "szabadság", "szabin"]:
            if keyword in title:
                name = title.replace(keyword, "").strip()
                normalized_keyword = synonyms.get(keyword, "")
                name = f"{name} {normalized_keyword}".strip()

                # Handle special name cases
                name = name_synonyms.get(name, name)

                days_off_counter[name] += days_off

    return days_off_counter


# Initialize Google Calendar API client
service = get_calendar_service()
calendar_id = "qvorb8l2e3826f60mhlqpejc9k@group.calendar.google.com"

# List calendar data and get days off for each worker
days_off_counter = list_calendar_data(service, calendar_id)

# ... rest of your code for sorting and plotting remains unchanged

# List calendar data and get days off for each worker
days_off_counter = list_calendar_data(service, calendar_id)

# Print to CLI in human-readable form
# Find the longest name for text alignment
max_name_length = max(len(name) for name in days_off_counter.keys())

# Sort the data by days off
sorted_days_off_counter = {
    k: v
    for k, v in sorted(days_off_counter.items(), key=lambda item: item[1])
}

# Print to CLI in a more aligned, human-readable form
for name, days_off in sorted_days_off_counter.items():
    print(
        f"{name.ljust(max_name_length)}: {'#' * int(days_off)} ({days_off} days)"
    )

import seaborn as sns
import matplotlib.pyplot as plt

# Generate a Seaborn barplot

plt.figure(figsize=(18, 8))
ax = sns.barplot(x=list(sorted_days_off_counter.keys()),
                 y=list(sorted_days_off_counter.values()),
                 hue=list(sorted_days_off_counter.keys()),
                 dodge=False,
                 palette="viridis")
plt.xlabel('Munkavállaló neve', fontsize=14)
plt.ylabel('Szabadnapok', fontsize=14)
plt.title('Szabadnapok munkavállalók szerint (Rendezett)', fontsize=16)
plt.xticks(rotation=45, ha='right', fontsize=12)
plt.yticks(fontsize=12)
plt.tight_layout()
plt.savefig('hungarian_adjusted_sorted_days_off_by_worker.png')
