import enum
from datetime import datetime

from app import db


class AlarmState(enum.Enum):
    UNKNOWN = 0
    OK = 1
    WARNING = 2
    CRITICAL = 3


class Alarm(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    target = db.Column(db.String(60), nullable=False)
    group_id = db.Column(db.Integer, db.ForeignKey("group.id"))
    origin_id = db.Column(db.Integer, db.ForeignKey("origin.id"))
    proxy_id = db.Column(db.Integer, db.ForeignKey("proxy.id"))
    bridge_id = db.Column(db.Integer, db.ForeignKey("bridge.id"))
    alarm_type = db.Column(db.String(255), nullable=False)
    alarm_state = db.Column(db.Enum(AlarmState), default=AlarmState.UNKNOWN, nullable=False)
    state_changed = db.Column(db.DateTime(), nullable=False)
    last_updated = db.Column(db.DateTime())
    text = db.Column(db.String(255))

    group = db.relationship("Group", back_populates="alarms")
    origin = db.relationship("Origin", back_populates="alarms")
    proxy = db.relationship("Proxy", back_populates="alarms")
    bridge = db.relationship("Bridge", back_populates="alarms")

    @classmethod
    def csv_header(cls):
        return [
            "id", "target", "group_id", "origin_id", "proxy_id", "bridge_id", "alarm_type",
            "alarm_state", "state_changed", "last_updated", "text"
        ]

    def csv_row(self):
        return [
            getattr(self, x) for x in self.csv_header()
        ]

    def update_state(self, state: AlarmState, text: str):
        if self.alarm_state != state or self.state_changed is None:
            self.state_changed = datetime.utcnow()
        self.alarm_state = state
        self.text = text
        self.last_updated = datetime.utcnow()
        db.session.commit()
