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

class SimplePoll(Poll):
    """Poll with only one answer allowed"""

    __tablename__ = 'simplepoll'

    # Names of templates
    template = 'simplepoll.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, data):
        data = [data] # TODO
        answer = PollAnswer(user, data)
        return answer

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


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