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

from api.DatabaseHandler import DatabaseHandler

'''

Endpoint vracejici data o vsech zasedanich

'''

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

    # ziskani potrebnych dat
    orderZMB = 8
    data = []

    # ucast na jednotlivych zasedanich jako JOIN s pomocnou tabulkou _attendancestats
    sql = "SELECT CASE when hlasovani.cislo_zasedani<10 then LPAD(hlasovani.cislo_zasedani, 2, 0) else hlasovani.cislo_zasedani END AS cislo_zasedani, DATE_FORMAT(datum_zasedani,'%d.%m.%Y') AS datum, COUNT(*) AS pocet_platnych_hlasovani, _attendancestats.ucast FROM zmb JOIN zasedani_zmb ON zmb.poradi_ZMB = zasedani_zmb.ck_poradi_ZMB JOIN hlasovani ON zmb.poradi_ZMB = hlasovani.ck_poradi_ZMB JOIN _attendancestats ON _attendancestats.poradi_zmb=hlasovani.cislo_zasedani WHERE zmb.poradi_ZMB=%s AND zasedani_zmb.cislo_zasedani = hlasovani.cislo_zasedani AND hlasovani.validni_hlasovani=1 GROUP BY hlasovani.cislo_zasedani ORDER BY cislo_zasedani DESC"
    dbHandler.cursor.execute(sql, (orderZMB,))

    for cislo_zasedani, datum, pocet_platnych_hlasovani, ucast in dbHandler.cursor:
        data.append({'cislo_zasedani': cislo_zasedani, 'datum': datum, 'pocet_platnych_hlasovani': pocet_platnych_hlasovani, 'ucast': ucast})
        
    # ukonceni spojeni s db
    dbHandler.closeConnection()
    
    return data