import enum

from typing import Optional, List

import pymongo.collection
from bson import ObjectId
from django.conf import settings
from django.utils import timezone
from pymongo.cursor import Cursor

from idm.utils import mongo


_DEFAULT = object()


class EventType(enum.Enum):
    YT_EXPORT_REQUIRED = 'yt_export_required'


def _get_collection() -> pymongo.collection.Collection:
    return mongo.get_mongo_db()[settings.MONGO_EVENTS_COLLECTION]


def add_event(event_type: EventType, system_id: int, role_id: Optional[int] = None):
    collection = _get_collection()
    collection.insert_one(dict(
        added=timezone.now(),
        event=event_type.value,
        system_id=system_id,
        role_id=role_id,
    ))


def get_events(event_type: EventType = _DEFAULT, system_id: int = _DEFAULT) -> Cursor:
    collection = _get_collection()
    filter_data = {}
    if event_type is not _DEFAULT:
        filter_data['event'] = event_type and event_type.value
    if system_id is not _DEFAULT:
        filter_data['system_id'] = system_id
    return collection.find(filter_data)


def remove_events(id_list: List[ObjectId]):
    collection = _get_collection()
    collection.delete_many({'_id': {'$in': id_list}})
