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

from api.DatabaseHandler import DatabaseHandler

'''

Pomocny endpoint na vypocet sumarnich odpovedi kazde politicke strany

'''

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

    orderZMB = 8

    sql = "DELETE FROM _partiesStats"
    dbHandler.cursor.execute(sql)
    
    sql = "INSERT INTO _partiesStats SELECT ck_politicka_strana, CASE when text=REPLACE(text, ' (VK)', '') then text else REPLACE(text, ' (VK)', '') END AS modifiedText, SUM(count) AS sum FROM (SELECT prislusi_k.ck_politicka_strana, vysledek_volice.text, COUNT(*) AS count FROM zasedani_zmb JOIN hlasovani ON zasedani_zmb.ck_poradi_ZMB = hlasovani.ck_poradi_ZMB JOIN hlasovani_clena ON hlasovani.id = hlasovani_clena.ck_cislo_hlasovani JOIN vysledek_volice ON hlasovani_clena.ck_vysledek_volice = vysledek_volice.id JOIN clen_zmb ON hlasovani_clena.ck_clen_ZMB = clen_zmb.id JOIN prislusi_k ON clen_zmb.id = prislusi_k.ck_clen_ZMB WHERE zasedani_zmb.ck_poradi_ZMB=%s AND zasedani_zmb.cislo_zasedani=hlasovani.cislo_zasedani AND hlasovani.validni_hlasovani=1 AND zasedani_zmb.datum_zasedani BETWEEN prislusi_k.datum_od AND prislusi_k.datum_do GROUP BY prislusi_k.ck_politicka_strana, vysledek_volice.text ORDER BY prislusi_k.ck_politicka_strana) AS T1 GROUP BY ck_politicka_strana, modifiedText"
    dbHandler.cursor.execute(sql, (orderZMB, ))

    # ukonceni spojeni s db
    dbHandler.closeConnection()
    
    return 'tabulka _partiesStats byla uspesne aktualizovana'