from app import db
from app.models import AbstractConfiguration, AbstractResource


class Origin(AbstractConfiguration):
    group_id = db.Column(db.Integer, db.ForeignKey("group.id"), nullable=False)
    domain_name = db.Column(db.String(255), unique=True, nullable=False)
    auto_rotation = db.Column(db.Boolean, nullable=False)

    group = db.relationship("Group", back_populates="origins")
    mirrors = db.relationship("Mirror", back_populates="origin")
    proxies = db.relationship("Proxy", back_populates="origin")
    alarms = db.relationship("Alarm", back_populates="origin")

    @classmethod
    def csv_header(cls):
        return super().csv_header() + [
            "group_id", "domain_name"
        ]

    def destroy(self):
        super().destroy()
        for proxy in self.proxies:
            proxy.destroy()


class Proxy(AbstractResource):
    origin_id = db.Column(db.Integer, db.ForeignKey("origin.id"), nullable=False)
    provider = db.Column(db.String(20), nullable=False)
    psg = db.Column(db.Integer, nullable=True)
    slug = db.Column(db.String(20), nullable=True)
    terraform_updated = db.Column(db.DateTime(), nullable=True)
    url = db.Column(db.String(255), nullable=True)

    origin = db.relationship("Origin", back_populates="proxies")
    alarms = db.relationship("Alarm", back_populates="proxy")

    @classmethod
    def csv_header(cls):
        return super().csv_header() + [
            "origin_id", "provider", "psg", "slug", "terraform_updated", "url"
        ]


class Mirror(AbstractResource):
    origin_id = db.Column(db.Integer, db.ForeignKey("origin.id"), nullable=False)
    url = db.Column(db.String(255), unique=True, nullable=False)

    origin = db.relationship("Origin", back_populates="mirrors")

    @classmethod
    def csv_header(cls):
        return super().csv_header() + [
            "origin_id", "url"
        ]
