# -*- coding: utf-8 -*-
#
# Copyright (C) 2020 Avencall
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>
from sqlalchemy import select, func, UniqueConstraint
from sqlalchemy.orm import relationship, column_property
from sqlalchemy.schema import Column, PrimaryKeyConstraint
from sqlalchemy.types import Integer, String, Text

from xivo_dao.alchemy import UserLabels
from xivo_dao.helpers.db_manager import Base


class Labels(Base):
    __tablename__ = 'labels'
    __table_args__ = (
        PrimaryKeyConstraint('id'),
        UniqueConstraint('display_name')
    )

    id = Column(Integer, nullable=False, autoincrement=True)
    display_name = Column(String(128), nullable=False, unique=True)
    description = Column(Text)

    user_features = relationship("UserFeatures", secondary="userlabels", back_populates="labels")

    users_count = column_property(
        select([func.count(UserLabels.id)])
        .where(UserLabels.label_id == id)
        .correlate_except(UserLabels)
    )
