from sqlalchemy import Table
from sqlalchemy.dialects.postgresql import UUID
import uuid

import Models
from app import db

chatting_table = Table('chatting', Models.Base.metadata,
                       db.Column('user_id', db.ForeignKey('user.id')),
                       db.Column('chat_id', db.ForeignKey('chats.id')))


class ChatModel(Models.Base):
    __tablename__ = 'chats'

    id = db.Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    users = db.relationship(
        "UserModel",
        secondary=chatting_table,
        back_populates="chats"
    )
    channel_id = db.Column(db.ForeignKey('channel.id'), nullable=False)
    channel = db.relationship(
        "ChannelModel",
        cascade="all, delete-orphan",
        single_parent=True
    )

    def get_other_user(self, user):
        for user_in_chat in self.users:
            if user_in_chat != user:
                return user_in_chat
