import datetime
from typing import Optional, List

from app.brm.brn import BRN
from app.extensions import db
from app.models.alarms import Alarm


def alarms_for(target: BRN) -> List[Alarm]:
    return list(Alarm.query.filter(
        Alarm.target == str(target)
    ).all())


def _get_alarm(target: BRN,
               aspect: str,
               create_if_missing: bool = True) -> Optional[Alarm]:
    target_str = str(target)
    alarm: Optional[Alarm] = Alarm.query.filter(
        Alarm.aspect == aspect,
        Alarm.target == target_str
    ).first()
    if create_if_missing and alarm is None:
        alarm = Alarm()
        alarm.aspect = aspect
        alarm.target = target_str
        alarm.text = "New alarm"
        alarm.state_changed = datetime.datetime.utcnow()
        alarm.last_updated = datetime.datetime.utcnow()
        db.session.add(alarm)
    return alarm


def get_alarm(target: BRN, aspect: str) -> Optional[Alarm]:
    return _get_alarm(target, aspect, create_if_missing=False)


def get_or_create_alarm(target: BRN, aspect: str) -> Alarm:
    alarm = _get_alarm(target, aspect, create_if_missing=True)
    if alarm is None:
        raise RuntimeError("Asked for an alarm to be created but got None.")
    return alarm
