from flask_restful import Api, Resource, reqparse
import mysql.connector

from api.DatabaseHandler import DatabaseHandler

'''

Endpoint vracejici sumarni odpovedi kazde politicke strany

'''

class PartiesStats(Resource):
  def get(self):
    
    # navazani spojeni s db
    dbHandler = DatabaseHandler()

    # ziskani potrebnych dat
    orderZMB = 8
    data = []

    sql = "SELECT DISTINCT politicka_strana.id, politicka_strana.zkratka, politicka_strana.barva FROM politicka_strana JOIN prislusi_k ON politicka_strana.id=prislusi_k.ck_politicka_strana WHERE ck_poradi_ZMB=%s ORDER BY politicka_strana.zkratka"
    dbHandler.cursor.execute(sql, (orderZMB,))

    for item in dbHandler.cursor:
        data.append({"strana_id": item[0], "strana_zkratka": item[1], "strana_barva": item[2], "celkove_hlasy": []})

    sql = "SELECT * FROM _partiesstats"
    dbHandler.cursor.execute(sql)

    summaries = {}
    for item in dbHandler.cursor:
        if item[0] not in summaries:
            summaries[item[0]] = {'ano': 0, 'ne': 0, 'zdržel se': 0, 'nehlasoval': 0, 'nepřít.': 0}
        summaries[item[0]][item[1].lower()] = int(item[2])

    for party in data:
        party["celkove_hlasy"] = summaries[party["strana_id"]]

        totalCount = 0
        for key in summaries[party["strana_id"]]:
            totalCount = totalCount + summaries[party["strana_id"]][key]
        
        party["celkova_ucast"] = int((totalCount - summaries[party["strana_id"]]['nepřít.']) / totalCount * 100)

    # ukonceni spojeni s db
    dbHandler.closeConnection()
    
    return data