import datetime
import enum

from app.brm.brn import BRN
from app.extensions import db
from app.models import AbstractConfiguration, AbstractResource


class AutomationState(enum.Enum):
    IDLE = 0
    RUNNING = 1
    ERROR = 3


class Automation(AbstractConfiguration):
    short_name = db.Column(db.String(25), nullable=False)
    state = db.Column(db.Enum(AutomationState), default=AutomationState.IDLE, nullable=False)
    enabled = db.Column(db.Boolean, nullable=False)
    last_run = db.Column(db.DateTime(), nullable=True)
    next_run = db.Column(db.DateTime(), nullable=True)
    next_is_full = db.Column(db.Boolean(), nullable=False)

    logs = db.relationship("AutomationLogs", back_populates="automation")

    @property
    def brn(self) -> BRN:
        return BRN(
            group_id=0,
            product="core",
            provider="",
            resource_type="automation",
            resource_id=self.short_name
        )

    def kick(self) -> None:
        self.enabled = True
        self.next_run = datetime.datetime.utcnow()
        self.updated = datetime.datetime.utcnow()


class AutomationLogs(AbstractResource):
    automation_id = db.Column(db.Integer, db.ForeignKey(Automation.id), nullable=False)
    logs = db.Column(db.Text)

    automation = db.relationship("Automation", back_populates="logs")

    @property
    def brn(self) -> BRN:
        return BRN(
            group_id=0,
            product="core",
            provider="",
            resource_type="automationlog",
            resource_id=self.id
        )
