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

from api.DatabaseHandler import DatabaseHandler
from api.MemberData import MemberData

'''

Endpoint vracejici vseobecne informace o politickych stranach 
v ramci zastupitelstva

'''

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

    # ziskani potrebnych dat
    orderZMB = 8
    data = []

    sql = "SELECT cislo_zasedani, DATE_FORMAT(datum_zasedani,'%d.%m.%Y') FROM zasedani_zmb WHERE ck_poradi_ZMB=%s ORDER BY `datum_zasedani` DESC"
    dbHandler.cursor.execute(sql, (orderZMB,))
    row = dbHandler.cursor.fetchone()
    dateOfLastSession = str(row[1]).split(".")
    dateOfLastSession = dateOfLastSession[2] + '-' + dateOfLastSession[1] + '-' + dateOfLastSession[0]
    
    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], "clenove": []})

    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:
        for party in data:
            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})

    for party in data:
        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

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