from __future__ import annotations

from typing import List

from pycs import db
from pycs.database.base import NamedBaseModel

class Collection(NamedBaseModel):

    # table columns
    project_id = db.Column(
        db.Integer,
        db.ForeignKey("project.id", ondelete="CASCADE"),
        nullable=False)

    reference = db.Column(
        db.String, nullable=False)

    description = db.Column(
        db.String)

    position = db.Column(
        db.Integer, nullable=False)

    autoselect = db.Column(
        db.Boolean, nullable=False)


    # contraints
    __table_args__ = (
        db.UniqueConstraint('project_id', 'reference'),
    )

    # relationships to other models
    files = db.relationship("File", backref="collection", lazy="dynamic")

    serialize_only = NamedBaseModel.serialize_only + (
        "project_id",
        "reference",
        "description",
        "position",
        "autoselect",
    )

    def count_files(self) -> int:
        return self.files.count()

    def get_files(self, offset: int = 0, limit: int = -1):
        """
        get an iterator of files associated with this project

        :param offset: file offset
        :param limit: file limit
        :return: iterator of files
        """
        from pycs.database.File import File
        return self.files.order_by(File.id).offset(offset).limit(limit)


    @staticmethod
    def update_autoselect(collections: List[Collection]) -> List[Collection]:
        """ disable autoselect if there are no elements in the collection """

        found = False

        for collection in collections:
            if not collection.autoselect:
                continue

            if found:
                collection.autoselect = False

            elif collection.count_files() == 0:
                collection.autoselect = False
                found = True

        return collections