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

from api.DatabaseHandler import DatabaseHandler

'''

Endpoint vracejici data o konkretnim zasedani

'''

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

    # ziskani potrebnych dat
    orderZMB = 8
    sessionId = session_id
    data = {
        'cislo_zasedani': sessionId,
        'pocet_hlasovani': {
            'platna': 0,
            'neplatna': 0,
            'prijata': 0,
            'neprijata': 0
        },
        'video_zaznam': []
    }

    # (ne)platna hlasovani
    sql = "SELECT DATE_FORMAT(datum_zasedani,'%d.%m.%Y') AS datum, hlasovani.validni_hlasovani, COUNT(hlasovani.validni_hlasovani) as pocet 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 vysledek_hlasovani ON hlasovani.ck_vysledek_hlasovani = vysledek_hlasovani.id WHERE zmb.poradi_ZMB=%s AND zasedani_zmb.cislo_zasedani = hlasovani.cislo_zasedani AND zasedani_zmb.cislo_zasedani=%s GROUP BY hlasovani.validni_hlasovani"
    dbHandler.cursor.execute(sql, (orderZMB, session_id))

    # kontrola existence ID
    if dbHandler.cursor.rowcount == 0:
        return {'error': 'neexistujici ID'}
    else:
        for datum, validni_hlasovani, pocet in dbHandler.cursor:
            data['datum'] = datum

            if validni_hlasovani == 1:
                data['pocet_hlasovani']['platna'] = pocet
            else:
                data['pocet_hlasovani']['neplatna'] = pocet

    # (ne)prijata platna hlasovani
    sql = "SELECT DATE_FORMAT(datum_zasedani,'%d.%m.%Y') AS datum, vysledek_hlasovani.text, COUNT(vysledek_hlasovani.text) as pocet 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 vysledek_hlasovani ON hlasovani.ck_vysledek_hlasovani = vysledek_hlasovani.id WHERE zmb.poradi_ZMB=%s AND zasedani_zmb.cislo_zasedani = hlasovani.cislo_zasedani AND zasedani_zmb.cislo_zasedani=%s AND hlasovani.validni_hlasovani=1 GROUP BY vysledek_hlasovani.text"
    dbHandler.cursor.execute(sql, (orderZMB, session_id))

    for datum, text, pocet in dbHandler.cursor:
        if text == 'Přijato':
                data['pocet_hlasovani']['prijata'] = pocet
        else:
            data['pocet_hlasovani']['neprijata'] = pocet

    # videa
    sql = "SELECT url FROM `zasedani_zmb_video` WHERE ck_zasedani_zmb=%s"
    dbHandler.cursor.execute(sql, (session_id,))

    if dbHandler.cursor.rowcount != 0:
        for url in dbHandler.cursor:
            data['video_zaznam'].append({'url': url})

    sql = "SELECT ucast FROM `_attendancestats` WHERE poradi_zmb=%s"
    dbHandler.cursor.execute(sql, (session_id,))
    row = dbHandler.cursor.fetchone()
    data['ucast'] = row[0]

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