import uuid

from sqlalchemy.dialects.postgresql import UUID

import Models
from app import db


class InfoNuggetDataClass:
    def __init__(self, nugget_id, answer):
        nugget = InfoNuggetModel.query.get(nugget_id)
        if not nugget:
            raise Models.InvalidIDException
        self.id = nugget.id
        self.answer_id = nugget.get_answer_id(answer)


class InfoNuggetModel(Models.Base):
    __tablename__ = 'info_nuggets'

    id = db.Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    name = db.Column(db.String, nullable=False)
    answers_en = db.Column(db.ARRAY(db.String), nullable=False)
    answers_de = db.Column(db.ARRAY(db.String), nullable=False)

    def get_all_answers(self, lang):
        if 'de' in lang:
            return self.answers_de
        return self.answers_en

    def get_answer_id(self, answer):
        if answer in self.answers_en:
            return self.answers_en.index(answer)
        if answer in self.answers_de:
            return self.answers_de.index(answer)
        return 0

    def get_answer_string(self, answer_id, lang):
        if lang and 'de' in lang:
            answers = self.answers_de
        else:
            answers = self.answers_en
        if answer_id < 0:
            answer_id = 0
        if answer_id >= len(answers):
            answer_id = len(answers) - 1
        return answers[answer_id]

    @classmethod
    def from_string(cls, name):
        return cls.query.filter(cls.name == name).first()
