from app import db
from app.models.poll import Poll, PollAnswer
from collections import Counter
from itertools import chain


class MultiplePoll(Poll):
    """Poll with many answers allowed"""

    __tablename__ = 'multiplepoll'

    # Names of templates
    template = 'multiplepoll.html'

    __mapper_args__ = {
        'polymorphic_identity': __tablename__,
    }

    def __init__(self, author, title, choices, **kwargs):
        choices = [Choice(i, t) for i, t in enumerate(choices)]
        super().__init__(author, title, choices, **kwargs)

    # Mandatory methods
    def vote(self, user, request):
        answers_id = []
        for c in self.choices:
            if f"pollanswers-{c.id}" in request.form:
                answers_id.append(c.id)
        return PollAnswer(self, user, answers_id)

    @property
    def results(self):
        values = {c: 0 for c in self.choices}
        counter = Counter(values)
        for a in self.answers:
            counter.update([self.choice_from_id(id) for id in a.answer])
        return counter

    # Custom method
    def choice_from_id(self, id):
        for c in self.choices:
            if c.id == id:
                return c
        return None

class Choice():
    def __init__(self, id, title):
        self.id = id
        self.title = title
