import json
import uuid
from dataclasses import dataclass

from sqlalchemy.dialects.postgresql import UUID

import Models
from app import db


class PanelModel(Models.Base):
    __tablename__ = 'panel'

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

    __mapper_args__ = {
        'polymorphic_on': type,
        'polymorphic_identity': "panel",
    }

    id = db.Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    card_id = db.Column(db.ForeignKey('card.id'), nullable=False)
    card = db.relationship(
        "CardModel",
        foreign_keys=card_id,
        back_populates="panels"
    )
    position = db.Column(db.Integer, nullable=False)


class DescriptionPanelModel(PanelModel):
    __mapper_args__ = {
        'polymorphic_identity': "description_panel",
    }

    @property
    def text(self):
        return self.card.user.personal_information.description


class InterestsPanelModel(PanelModel):
    __mapper_args__ = {
        'polymorphic_identity': "interests_panel",
    }

    def get_bubbles(self, lang):
        bubbles = []
        for i in self.card.user.personal_information.interest_list:
            bubbles.append(Bubble(i.id,
                                  "",
                                  i.get_name(lang)))
        return bubbles


class ImagePanelModel(PanelModel):
    __mapper_args__ = {
        'polymorphic_identity': "image_panel",
    }

    image_id = db.Column(db.ForeignKey('image.id'), nullable=True)
    image = db.relationship(
        "ImageModel",
        foreign_keys=image_id
    )


class InfoNuggetsPanelModel(PanelModel):
    __mapper_args__ = {
        'polymorphic_identity': "info_nuggets_panel",
    }

    nuggets = db.Column(db.String, nullable=True)

    def set_nuggets(self, input_nuggets):
        nuggets = []
        for nugget in input_nuggets:
            nuggets.append((str(nugget.id), nugget.answer_id))
        self.nuggets = json.dumps(nuggets)

    def get_bubbles(self, lang):
        data = json.loads(self.nuggets)
        bubbles = []
        for i in data:
            nugget = Models.InfoNuggetModel.query.get(i[0])
            bubbles.append(Bubble(nugget.id,
                                  nugget.name,
                                  nugget.get_answer_string(i[1], lang)))
        return bubbles


class QuestionPanelModel(PanelModel):
    __mapper_args__ = {
        'polymorphic_identity': "question_panel",
    }

    question_id = db.Column(db.ForeignKey('questions.id'), nullable=True)
    question = db.relationship(
        "QuestionsModel",
        foreign_keys=question_id
    )
    answer = db.Column(db.String, nullable=True)


class TextPanelModel(PanelModel):
    __mapper_args__ = {
        'polymorphic_identity': "text_panel",
    }

    text = db.Column(db.String, nullable=True)


@dataclass
class Bubble:
    id: UUID
    icon: str
    text: str
