from datetime import datetime

from app import db
from app.models import AbstractResource


class BridgeConf(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    group_id = db.Column(db.Integer, db.ForeignKey("group.id"), nullable=False)
    provider = db.Column(db.String(20), nullable=False)
    method = db.Column(db.String(20), nullable=False)
    description = db.Column(db.String(255))
    number = db.Column(db.Integer())
    added = db.Column(db.DateTime(), default=datetime.utcnow, nullable=False)
    updated = db.Column(db.DateTime(), default=datetime.utcnow, nullable=False)
    destroyed = db.Column(db.DateTime(), nullable=True)

    group = db.relationship("Group", back_populates="bridgeconfs")
    bridges = db.relationship("Bridge", back_populates="conf")

    def destroy(self):
        self.destroyed = datetime.utcnow()
        self.updated = datetime.utcnow()
        for bridge in self.bridges:
            if bridge.destroyed is None:
                bridge.destroyed = datetime.utcnow()
                bridge.updated = datetime.utcnow()
        db.session.commit()


class Bridge(AbstractResource):
    conf_id = db.Column(db.Integer, db.ForeignKey("bridge_conf.id"), nullable=False)
    terraform_updated = db.Column(db.DateTime(), nullable=True)
    nickname = db.Column(db.String(255), nullable=True)
    fingerprint = db.Column(db.String(255), nullable=True)
    hashed_fingerprint = db.Column(db.String(255), nullable=True)
    bridgeline = db.Column(db.String(255), nullable=True)

    conf = db.relationship("BridgeConf", back_populates="bridges")
    alarms = db.relationship("Alarm", back_populates="bridge")
