from voters import *

class approval():
    voters = None
    candidates = None
    scores = None #assigns points given the positioning on each ballot.
    num_cands = None
    weights = None
    type = None

    def __init__(self, voters, type='approval'):
        """
        Calculates the approval winner by assigning all candidates before the
        cutoff point 1 point each.
        """
        self.voters = voters
        self.type = type        
        self.candidates = voters.cands.candidates
        self.num_cands = len(self.candidates)
        self.scores = {}
        self.weight_vector(type)

    def __str__(self):
        w = self.winner()
        if self.type == 'approval':
            if len(w) == 1:
                return "Approval winner: %s" % w
            else:
                return "Approval tie: %s" % w
        else:
            if self.type == 'even_and_equal':
                if len(w) == 1:
                    return "Even and equal winner: %s" % w
                else:
                    return "Even and equal tie: %s" % w


    def score(self):
        for c in self.candidates:
            self.scores[c] = 0
        for voter in self.voters.votes:
            for i in range(0, voter.cutoff):
                if self.type == 'approval':
                    self.scores[voter.ballot[i]] += self.weights[i]
                else:
                    if self.type == 'even_and_equal':
                        self.scores[voter.ballot[i]] += 1.0/voter.cutoff
        return self.scores

    def weight_vector(self, type):
        self.weights = []
        if type == 'approval':
            for i in range(1, len(self.candidates)+1):
                self.weights.append(1)
        if type == 'even_and_equal': #this is really deprecated.
            for i in range(1, len(self.candidates)+1):
                self.weights.append(1.0/i)

    def winner(self):
        self.score()
        top  = []
        val = 0
        #if self.type == 'approval':
            #print "Approval:"
        #else:
            #if self.type == 'even_and_equal':
                #print "Size approval even and equal:"
        #print self.scores
        for v in self.scores.itervalues():
            if v > val:
                val = v
        for k,v in self.scores.iteritems():
            if v == val:
                top.append(k)
        return top


