from models import db, ma
from models.audio import Album
from models.audio.meta import WritableField, SmartCollageField
from webargs import Arg

smart_collage_album_association_table = db.Table(
    "smart_collage_albums",
    db.Column('album_id', db.Integer,
              db.ForeignKey("album.id", ondelete='cascade')),
    db.Column('collage_id', db.Integer,
              db.ForeignKey("smart_collage.id", ondelete='cascade'))
)

smart_collage_smart_rules_association_table = db.Table(
    "smart_collage_rules",
    db.Column('smart_collage_id', db.Integer,
              db.ForeignKey("smart_collage.id", ondelete='cascade')),
    db.Column('smart_rule_id', db.Integer,
              db.ForeignKey("smart_rule.id", ondelete='cascade'))
)


class SmartCollage(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)
    private = db.Column(db.Boolean)

    owner = db.relationship("User", uselist=False, backref="smart_collages")
    owner_id = db.Column(db.Integer, db.ForeignKey("user.id", ondelete="cascade"))

    albums = db.relationship("Album", secondary=smart_collage_album_association_table)

    rules = db.relationship("SmartRule", secondary=smart_collage_smart_rules_association_table)
    connector = db.Column(db.String)
    sort_by = db.Column(db.String)

    def __init__(self, owner, name, rules=None):
        self.owner = owner
        self.name = name
        self.albums = []
        self.private = True
        self.rules = rules if rules is not None else []


class SmartCollageSchema(ma.Schema):
    id = ma.Integer()
    name = ma.Str()
    private = ma.Bool()
    owner = ma.Nested("UserSchema", only=["id", "username"])
    albums = ma.Nested("AlbumSchema", many=True, only=["id", "title", "albumartist", "albumart", "tracks"])
    writable = WritableField(attribute="owner_id")
    connector = ma.Str()
    rules = ma.Nested("SmartRuleSchema", many=True)
    sort_by = ma.Str()
    smart = SmartCollageField(attribute="id")
