import pandas as pd
import psycopg2 as pg
import subprocess as sp
import matplotlib.pyplot as plt

# psql -h londres -d dblolaborie -U lolaborie -W

data = pd.read_csv(r'Report_2022.csv')
df = pd.DataFrame(data)
df2 = df.drop_duplicates()
df2 = df2.dropna()

data = pd.read_csv(r'Report_2021.csv')
df = pd.DataFrame(data)
df2021 = df.drop_duplicates()
df2021 = df.dropna()

data = pd.read_csv(r'Report_2020.csv')
df = pd.DataFrame(data)
df2020 = df.drop_duplicates()
df2020 = df.dropna()

regions = []

for row in df2.itertuples():
    if row.Region not in regions:
        regions.append(row.Region)




sp.run(["stty", "-echo"])

mdp = input("Le mot de passe stp : ")

sp.run(["stty", "echo"])

co = None
print("Connexion...\n")
try:
    # Connexion à la base
    # Attention ! pensez à remplacer dblogin , login et mot_de_passe
    #avec vos informations
    co = pg.connect(host='londres',
                    database ='dblolaborie',
                    user='lolaborie',
                    password = mdp)
    
    curs = co.cursor()

    curs.execute('''DROP TABLE IF EXISTS Pays,Region,Annee,Statistique CASCADE;''')

    curs.execute('''CREATE TABLE Region(
                    nom varchar(30) PRIMARY KEY);''')

    curs.execute('''CREATE TABLE Pays(
                    code varchar(3) PRIMARY KEY,
                    nom varchar(30) NOT NULL,
                    nomR varchar(30) NOT NULL REFERENCES Region);''')

    curs.execute('''CREATE TABLE Annee(
                    annee varchar(4) PRIMARY KEY);''')

    curs.execute('''CREATE TABLE Statistique(
                    annee varchar(4) NOT NULL REFERENCES Annee,
                    codeP varchar(3) NOT NULL REFERENCES Pays,
                    position numeric NOT NULL,
                    gscore numeric,
                    pscore numeric,
                    escore numeric,
                    lscore numeric,
                    soscore numeric,
                    sescore numeric,
                    jkill numeric NOT NULL,
                    mkill numeric NOT NULL,
                    jprison numeric NOT NULL,
                    mprison numeric NOT NULL,
                    situation varchar(30) NOT NULL,
                    PRIMARY KEY(annee,codeP));''')
    print("Tables crées !\n")
    curs.execute('''INSERT INTO Annee VALUES('2022');''')
    curs.execute('''INSERT INTO Annee VALUES('2021');''')
    curs.execute('''INSERT INTO Annee VALUES('2020');''')
    print("Années insérées !")
    for r in regions:
        curs.execute('''INSERT INTO Region VALUES(%s);''',
                        (r, ))
    print("Régions insérées !")


    for row in df2.itertuples():
        curs.execute('''INSERT INTO Pays VALUES(%s,%s,%s);''',
                        (row.ISO_Code, row.Country, row.Region))
        curs.execute('''INSERT INTO Statistique VALUES('2022',%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s);''',
                        (row.ISO_Code,row.Position_2022,row.Global_Score,row.Politic_Score,row.Economic_Score,row.Legislative_Score,row.Social_Score,row.Security_Score,row.Journalist_Killed,row.Media_Workers_Killed,row.Journalist_Imprisoned,row.Media_Workers_Imprisoned,row.Situation))

    for row in df2021.itertuples():
        curs.execute('''INSERT INTO Statistique VALUES('2021',%s,%s,%s,NULL,NULL,NULL,NULL,NULL,%s,%s,%s,%s,%s);''',
                        (row.ISO_Code,row.Position_2021,row.Global_Score,row.Journalist_Killed,row.Media_Workers_Killed,row.Journalist_Imprisoned,row.Media_Workers_Imprisoned,row.Situation))
    
    for row in df2020.itertuples():
        curs.execute('''INSERT INTO Statistique VALUES('2020',%s,%s,%s,NULL,NULL,NULL,NULL,NULL,%s,%s,%s,%s,%s);''',
                        (row.ISO_Code,row.Position_2020,row.Global_Score,row.Journalist_Killed,row.Media_Workers_Killed,row.Journalist_Imprisoned,row.Media_Workers_Imprisoned,row.Situation))
    print("Insertions terminées !")
    co.commit()
    curs.close()
# Affichage du message d'erreur en cas de probl ème de connexion
except(Exception, pg.DatabaseError) as error :
    print(error)
# Attention ! Toujours fermer la connexion lorsqu 'on en a plus besoin
finally:
    if co is not None:
        co.close()