from typing import Optional, List
from .service import get_service
from googleapiclient.errors import HttpError

def get_events_between(start_datetime: str, end_datetime: str) -> List[dict]:
    """Gets events from Google Calendar between the given start and end datetime.
    Takes Start time and End time in ISO Format and will return the all events if any in that range.

    Args:
    start_datetime: Start datetime in ISO format (e.g., '2025-04-19T10:00:00Z')
    end_datetime: End datetime in ISO format (e.g., '2025-04-19T18:00:00Z')

    Returns:
        List: List of dictionaries containing events between start_datetime and end_datetime.

    Raises:
        Exception: For errors while getting events between start_datetime and end_datetime.

    Example:
        ```python
            def test_get_events_between():
                try:
                    events = get_events_between(
                        start_datetime="2025-09-01T00:00:00Z",
                        end_datetime="2025-09-30T11:59:59Z"
                    )
                    assert isinstance(events, List)
                    return f'Test case passed: {events}'
                except Exception as e:
                    return f'Error retrieving events: {e}'
        ```
    """
    try:
        service = get_service('calendar')
        events_result = (
            service.events()
            .list(
                calendarId= "primary",
                timeMin= start_datetime,
                timeMax= end_datetime,
                singleEvents=True,
                orderBy="startTime",
            )
            .execute()
        )
        events = events_result.get("items", [])
        return events
    except HttpError as error:
        raise Exception(f"An error occurred: {error}")

def create_event(start_datetime: str, end_datetime: str, 
                summary: str= "", description: Optional[str] = "", 
                location: Optional[str] = "") -> dict:
    """Creates an event in the Google Calendar if there is no event in that time slot.
    If there will be an existing event in that start and end time slot; It will not create another event and will return.
    Start Time, End Time, Summary is must; Description and Location are optional fields.

    Args:
    start_datetime: Start datetime in ISO format (e.g., '2025-04-19T10:00:00Z')
    end_datetime: End datetime in ISO format (e.g., '2025-04-19T12:00:00Z')
    summary: Summary or title of the event; what that event is about. It will be shown as title in the Google Calendar.
    description: Description of the event. It is the Optional field.
    location: Location of the Event. It is also an optional field.

    Returns:
        Dict: Dictionary containing events created.

    Raises:
        Exception: For errors while creating the event.
    
    Example:
    ```python
            def test_create_event():
                try:
                    event = create_event(
                        start_datetime="2025-09-16T10:00:00Z",
                        end_datetime="2025-09-16T12:00:00Z",
                        summary="Test Event",
                        description="This is a test event created for unit testing.",
                        location="Google Meet"
                    )
                    assert event is not None
                    return f'Test case passed: {event}'
                except Exception as e:
                    return f'Error creating event: {e}'
        ```
    """
    try:
        service = get_service('calendar')
        get_events= get_events_between(
            start_datetime= start_datetime,
            end_datetime= end_datetime
        )
        if get_events:
            return {'message': f'You already have an event between {start_datetime} and {end_datetime}.'}
        event = {
            "summary": summary,
            "location": location,
            "description": description,
            "start": {"dateTime": start_datetime, "timeZone": "UTC"},
            "end": {"dateTime": end_datetime, "timeZone": "UTC"},
        }
        
        created_event = service.events().insert(calendarId="primary", body=event).execute()
        return created_event
    except HttpError as error:
        raise Exception(f"An error occurred: {error}")

def delete_event(start_datetime: str, end_datetime: str) -> str:
    """Delete the event between the mentioned time if there is an event.

    Args:
    start_datetime: Start datetime in ISO format (e.g., '2025-04-19T10:00:00Z')
    end_datetime: End datetime in ISO format (e.g., '2025-04-19T18:00:00Z')

    Returns:
        Str: Confirmation of the deletion.

    Raises:
        Exception: For errors to delete the event.

    Example:
        ```python
            def test_delete_event():
                try:
                    deleted_event = delete_event(
                        start_datetime="2025-09-16T10:00:00Z",
                        end_datetime="2025-09-16T12:00:00Z")
                    return f'Test case passed: {deleted_event}'
                except Exception as e:
                    return f'Error retrieving events: {e}'
        ```
    """
    try:
        service= get_service('calendar')
        get_event= get_events_between(start_datetime= start_datetime,
                                      end_datetime= end_datetime)[0]
        if get_event:
            service.events().delete(calendarId= 'primary', eventId= get_event['id']).execute()
        return f"Event Delete Successfully!"
    except HttpError as error:
        raise Exception(f" Error {error}")