from PyQt5.uic import loadUi
from PyQt5.QtWidgets import *
from numpy import array
from pickle import load, dump

# ======================================================
# Module : Recherche
# Recherche un objet dans le fichier Objets.dat
# ======================================================
def Recherche():
    f = open("Objets.dat", "rb")
    name = w.Objet.text()

    found = False
    fin_fichier = False

    # Parcours du fichier
    while fin_fichier == False:
        try:
            ob = load(f)

            # Objet trouvé
            if ob['Objet'] == name:
                w.QR.setText(ob['QR'])
                w.QD.setText(ob['QD'])
                found = True

        except:
            fin_fichier = True

    # Objet inexistant
    if not found:
        QMessageBox.critical(w, "Erreur", "Objet inexistant")

    f.close()


# ======================================================
# Module : Tri
# Tri récursif du tableau selon le champ QD
# ======================================================
def Tri(tab, i, j):

    # Comparaison des deux extrémités
    if tab[i]['QD'] > tab[j - 1]['QD']:
        temp = tab[i]
        tab[i] = tab[j - 1]
        tab[j - 1] = temp

    # Appels récursifs
    if j - i > 2:
        k = (j - i) // 3
        Tri(tab, i, j - k)
        Tri(tab, i + k, j)
        Tri(tab, i, j - k)


# ======================================================
# Module : TriAffiche
# Trie le fichier puis affiche son contenu
# ======================================================
def TriAffiche():

    # Chargement du fichier dans un tableau
    tab = []

    f = open("Objets.dat", "rb")
    fin_fichier = False

    while fin_fichier == False:
        try:
            ob = load(f)
            tab += [ob]
        except:
            fin_fichier = True

    f.close()

    # Tri du tableau
    Tri(tab, 0, len(tab))

    # Sauvegarde du tableau trié
    f = open("Objets.dat", "wb")

    for i in range(len(tab)):
        dump(tab[i], f)

    f.close()

    # ==========================
    # Affichage selon le choix
    # ==========================
    preferance = w.cbChoix.currentText()

    if preferance == "Choisir une valeur":
        QMessageBox.critical(w, "Erreur", "Choisir l'option d'affichage")

    else:
        for i in range(len(tab)):

            if preferance == "Objet --- QR --- QD":
                w.list.addItem(
                    tab[i]['Objet'] + "- - -" +
                    tab[i]['QR'] + "- - -" +
                    tab[i]['QD']
                )

            elif preferance == "Objet --- QD":
                w.list.addItem(
                    tab[i]['Objet'] + "- - -" +
                    tab[i]['QD']
                )


# ======================================================
# Exploitation de l'interface graphique
# ======================================================
app = QApplication([])
w = loadUi("InterfManipulation.ui")

w.show()

# Bouton Rechercher
w.btRech.clicked.connect(Recherche)

# Bouton Trier et afficher
w.btTriAffich.clicked.connect(TriAffiche)

app.exec_()