from datetime import datetime
from typing import List

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


class BridgeConf(AbstractConfiguration):
    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)
    number = db.Column(db.Integer())

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

    @property
    def brn(self) -> BRN:
        return BRN(
            group_id=self.group_id,
            product="bridge",
            provider="",
            resource_type="bridgeconf",
            resource_id=str(self.id)
        )

    def destroy(self) -> None:
        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()

    @classmethod
    def csv_header(cls) -> List[str]:
        return super().csv_header() + [
            "group_id", "provider", "method", "description", "number"
        ]


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")

    @property
    def brn(self) -> BRN:
        return BRN(
            group_id=self.conf.group_id,
            product="bridge",
            provider=self.conf.provider,
            resource_type="bridge",
            resource_id=str(self.id)
        )

    @classmethod
    def csv_header(cls) -> List[str]:
        return super().csv_header() + [
            "conf_id", "terraform_updated", "nickname", "fingerprint", "hashed_fingerprint", "bridgeline"
        ]
