import psycopg2 as psy
import regles

def verifRegle(co):
    cur=co.cursor()
    cur.execute('''SELECT type,addresse,valeur FROM Status ORDER BY type,addresse;''')
    res=cur.fetchall()
    dataState={}
    for row in res:
        dataState[(row[0],int(row[1]))]=int(row[2])
    listRules=regles.getRegles()
    for rule in listRules:
        ruleWarning=0
        condition=len(rule[0])
        for i in rule[0]:
            if (i[0],i[1]) in dataState:
                if dataState[(i[0],i[1])]==i[2]:
                    ruleWarning+=1
        if ruleWarning>=condition:
            if (rule[1][0],rule[1][1]) in dataState:
                if dataState[(rule[1][0],rule[1][1])]==rule[1][2]:
                    return False
    return True
            
            


def ecritureBDD(lStatus,connec):
    co = None
    try:
        co = psy.connect(host=connec[0],database=connec[1],user=connec[2],password=connec[3])
        cur = co.cursor()
        for i in lStatus:
            cur.execute("INSERT INTO Status VALUES (%s,%s,%s ) ON CONFLICT (addresse,type) DO UPDATE SET valeur=%s;",(i[1],i[0],i[2],i[2]))
        if verifRegle(co):
            co.commit()
        else:
            print("A rule has been violated. The system is endangered. The database hasn't been updated.")
            co.rollback()
        cur.close()
    except(Exception,psy.DatabaseError) as error:
        print(error)
    finally:
        if co is not None:
            co.close()
