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

from api.DatabaseHandler import DatabaseHandler

'''

Endpoint vracejici data o konkretni politicke strane

'''

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

    # ziskani potrebnych dat
    orderZMB = 8
    sql = "SELECT datum_zasedani FROM zasedani_zmb WHERE ck_poradi_ZMB=%s ORDER BY `datum_zasedani` DESC"
    dbHandler.cursor.execute(sql, (orderZMB,))
    row = dbHandler.cursor.fetchone()
    dateOfLastSession = row[0]

    sql = "SELECT politicka_strana.zkratka, politicka_strana.nazev, politicka_strana.barva, COUNT(politicka_strana.zkratka) FROM prislusi_k JOIN clen_zmb ON prislusi_k.ck_clen_ZMB=clen_zmb.id JOIN politicka_strana ON prislusi_k.ck_politicka_strana=politicka_strana.id WHERE prislusi_k.ck_poradi_ZMB=%s AND politicka_strana.id=%s GROUP BY politicka_strana.zkratka ORDER BY COUNT(politicka_strana.zkratka) DESC"
    dbHandler.cursor.execute(sql, (orderZMB, party_id))
    
    # kontrola existence ID
    if dbHandler.cursor.rowcount == 0:
        return {'error': 'neexistujici ID'}
    else:
        row = dbHandler.cursor.fetchone()

    party = {
        'strana_id': party_id,
        'strana_zkratka': row[0],
        'strana_nazev': row[1], 
        'strana_barva': row[2],
        'pocet_aktivnich': 0,
        'pocet_neaktivnich': 0,
        'koalicni_strana': 0,
        'clenove': [],
        'dochazka': {}
    }

    sql = "SELECT * FROM `koalice` WHERE ck_politicka_strana=%s"
    dbHandler.cursor.execute(sql, (party_id,))
    if dbHandler.cursor.rowcount != 0:
        party['koalicni_strana'] = 1

    sql = "SELECT clen_zmb.id, politicka_strana.zkratka FROM politicka_strana JOIN prislusi_k ON politicka_strana.id=prislusi_k.ck_politicka_strana JOIN clen_zmb ON clen_zmb.id = prislusi_k.ck_clen_ZMB WHERE ck_poradi_ZMB=%s AND prislusi_k.datum_do=%s"
    dbHandler.cursor.execute(sql, (orderZMB, dateOfLastSession))
    activeMembersIds = []
    activeMembersIdParty = {}
    for item in dbHandler.cursor:
        activeMembersIds.append(item[0])
        activeMembersIdParty[item[0]] = item[1]
    
    sql = "SELECT DISTINCT politicka_strana.zkratka, clen_zmb.id, clen_zmb.jmeno_clena, clen_zmb.prijmeni_clena FROM politicka_strana JOIN prislusi_k ON politicka_strana.id=prislusi_k.ck_politicka_strana JOIN clen_zmb ON clen_zmb.id = prislusi_k.ck_clen_ZMB WHERE ck_poradi_ZMB=%s ORDER BY clen_zmb.prijmeni_clena"
    dbHandler.cursor.execute(sql, (orderZMB,))
    
    for item in dbHandler.cursor:
        if party["strana_zkratka"] == item[0]:
            state = 0
            if item[1] in activeMembersIds:
                if item[0] == activeMembersIdParty[item[1]]:
                    state = 1
            party["clenove"].append({"id":  item[1], "jmeno":  item[2] + ' ' +  item[3], "aktivni" : state})

    cntActive = 0
    for member in party["clenove"]:
        if member["aktivni"] == 1:
            cntActive = cntActive + 1
    party["pocet_aktivnich"] = cntActive
    party["pocet_neaktivnich"] = len(party["clenove"]) - cntActive

    sql = "SELECT datum_zasedani FROM zasedani_zmb WHERE ck_poradi_ZMB=%s"
    dbHandler.cursor.execute(sql, (orderZMB,))
    totalSessions = dbHandler.cursor.rowcount

    allDates = []
    for date in dbHandler.cursor:
        allDates.append(date[0])

    activeSessions = 0
    for date in allDates:
        sql = "SELECT ck_clen_ZMB FROM prislusi_k WHERE ck_poradi_ZMB=%s AND %s BETWEEN datum_od AND datum_do AND ck_politicka_strana=%s"
        dbHandler.cursor.execute(sql, (orderZMB, date, party_id))
        if dbHandler.cursor.rowcount > 0:
            activeSessions = activeSessions + 1
    
    party['dochazka']['celkem_zasedani'] = totalSessions
    party['dochazka']['mandat'] = activeSessions

    # sumarizace hlasu vsech clenu z dane politicke strany
    sql = "SELECT 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 AND prislusi_k.ck_politicka_strana=%s GROUP BY vysledek_volice.text"
    dbHandler.cursor.execute(sql, (orderZMB, party_id))

    summary = {}
    totalCount = 0
    countRemote = 0
    for text, count in dbHandler.cursor:
        summary[text.lower()] = count
        totalCount = totalCount + count
        if text.lower() in ['ano (vk)', 'ne (vk)', 'zdržel se (vk)', 'nehlasoval (vk)']:
                countRemote = countRemote + int(count)

    # korekce hlasu (slouceni prislusnych moznosti s/bez 'VK')
    keys = summary.keys()
    if 'ano' in keys:
        if 'ano (vk)' in keys:
            summary['ano'] = summary['ano'] + summary['ano (vk)']
            del summary['ano (vk)']
    if 'ne' in keys:
        if 'ne (vk)' in keys:
            summary['ne'] = summary['ne'] + summary['ne (vk)']
            del summary['ne (vk)']
    if 'zdržel se' in keys:
        if 'zdržel se (vk)' in keys:
            summary['zdržel se'] = summary['zdržel se'] + summary['zdržel se (vk)']
            del summary['zdržel se (vk)']
    if 'nehlasoval' in keys:
        if 'nehlasoval (vk)' in keys:
            summary['nehlasoval'] = summary['nehlasoval'] + summary['nehlasoval (vk)']
            del summary['nehlasoval (vk)']
    if 'nepřít.' in keys:
        if 'nepřít. (vk)' in keys:
            summary['nepřít.'] = summary['nepřít.'] + summary['nepřít. (vk)']
            del summary['nepřít. (vk)']

    party["celkove_hlasy"] = {key: value for key, value in sorted(summary.items())}
    
    '''
    party["celkova_ucast"] = {
        'prezenčně': totalCount-countRemote-summary['nepřít.']
    }
    if countRemote != 0:
        party['celkova_ucast']['distančně'] = countRemote
        
    if summary['nepřít.'] != 0:
        party['celkova_ucast']['nepřít.'] = summary['nepřít.']
    '''
    
    party["celkovy_pocet_hlasovani"] = totalCount
    party["celkovy_pocet_ucast"] = totalCount - summary['nepřít.']

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