from AppliDef import *
from tkcalendar import Calendar
import datetime


def DateFormat(j, m, a):
    jours = {0: "lundi", 1: "mardi", 2: "mercredi", 3: "jeudi", 4: "vendredi",
             5: "samedi", 6: "dimanche"}

    mois = {1: "janvier", 2: "février", 3: "mars", 4: "avril", 5: "mai", 6: "juin",
            7: "juillet", 8: "août", 9: "septembre", 10: "octobre", 11: "novembre",
            12: "décembre"}

    return "%s %d %s %d" % (jours[datetime.date(a, m, j).weekday()], j, mois[m], a)


def ConvertMois(m):
    mois = {"Janvier": 1, "Février": 2, "Mars": 3, "Avril": 4, "Mai": 5, "Juin": 6,
            "Juillet": 7, "Août": 8, "Septembre": 9, "Octobre": 10, "Novembre": 11,
            "Décembre": 12}
    return mois[m]


def FormatTP(TP):
    if len(TP) > 26:
        if len(TP) // 26 == 1:
            TP = TP[0:26] + '-\n' + TP[26:len(TP)]
        else:
            TPn = TP[0:26]
            for i in range(len(TP) // 26):
                if 26 + (i + 1) * 25 < len(TP):
                    TPn = TPn + '-\n' + TP[26 + i * 25:26 + (i + 1) * 25]
                else:
                    TPn = TPn + '-\n' + TP[26 + i * 25:len(TP)]
            TP = TPn
    return TP


def ChercheClasseTP(cur, TitreTP):
    cur.execute("select CLASSE from TP WHERE TITRE=\"" + TitreTP + "\"")
    ListClass = cur.fetchall()
    return ListClass[0][0]


def CherchePDFTP(cur, TitreTP):
    cur.execute("select PDF from TP WHERE TITRE=\"" + TitreTP + "\"")
    ListPDF = cur.fetchall()
    if len(ListPDF) > 0:
        PDF = ListPDF[0][0]
    else:
        PDF = ''
    return PDF


class FrmPlanningTP(tk.Toplevel):
    def __init__(self, container, RatioX, RatioY, Appli):
        tk.Toplevel.__init__(self, container)
        self.MainAppli = Appli
        self.parent = container
        self.RatioX = RatioX
        self.RatioY = RatioY
        self.FrmAgenda = None
        self.ClasseListe = self.MainAppli.ListClasses
        self.TitreClasse = None
        self.Classe = tk.StringVar()
        self.ListeClasse = None
        self.NbrGrListe = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
        self.TitreNbrGr = None
        self.NbrGr = tk.StringVar()
        self.ListeNbrGr = None
        self.DateLabel = None
        self.EntryTP = None
        self.ListBoxTP = None
        self.BtnOK, self.BtnAnnul, self.BtnSuiv, self.BtnPlus, self.BtnCloseMenu1 = None, None, None, None, None
        self.ListTP = []
        self.ListTPs = []
        self.ListTPDate = []
        self.AjoutNewTP = False
        self.IndexTP = 0
        self.TitreHoraire, self.LabelHDeb, self.TextHDeb, self.LabelMinDeb = None, None, None, None
        self.TextTiret, self.LabelHFin, self.LabelMinFin, self.TextHFin, = None, None, None, None
        self.PlanningJour, self.FrmPDF, self.NoPDF = None, None, None
        self.Note = None
        self.BtnPostit = None
        self.ListNoteDate = []
        self.AffichNote = False
        self.BtnCopier = None
        self.ActionCopieTP = False
        self.ListCopieTP = []

        screen = ctypes.windll.user32
        FrmFond = Image.open('Media/FrmAjout/Fond/Fond.jpg')
        self.SX = int((float(FrmFond.size[0]) * float(self.RatioX)))
        self.SY = int((float(FrmFond.size[1]) * float(self.RatioY)))

        coefY = float(ConfigResolution(self.MainAppli.Nconfig, 'YTitreFrm', self.MainAppli.curSave))

        self.ImgFrmFond = []
        self.ImgFrmFond = RedimImg(self.SX, self.SY, 'Media/FrmAjout/Fond/')
        self.CanvasFrmFond = CanvasApp(self, width=self.SX, height=self.SY)
        self.ImgCanvasFrmFond = self.CanvasFrmFond.create_image(0, 0, anchor=tk.NW, image=self.ImgFrmFond[0])

        self.geometry(str(self.SX) + "x" + str(self.SY) + "+" + str(int(screen.GetSystemMetrics(0) * 0.002)) + "+" +
                      str(int(screen.GetSystemMetrics(1) * 0.031)))
        self.resizable(width=False, height=False)
        self.overrideredirect(True)
        self.lift()

        self.ImgBtnClose, wsize, hsize, self.CanvasBtnClose, self.ImgCanvasBtnClose = CanInWindow(
            'Media/FrmAjout/BtnClose/', self.RatioX, self.RatioY, self.CanvasFrmFond, tk.CENTER,
            int(self.SX * 0.988), int(self.SY * 0.014), 0)
        ChangeCursor(self.CanvasBtnClose)
        self.CanvasBtnClose.bind('<Motion>',
                                 lambda action: self.CanvasBtnClose.itemconfig(self.ImgCanvasBtnClose,
                                                                               image=self.ImgBtnClose[1]))
        self.CanvasBtnClose.bind('<ButtonRelease-1>', self.CacheFrmPlanningTP)

        self.CanvasMenu1 = CanvasMenu(self.CanvasFrmFond, 'Media/FrmAjout/Menu/', int(self.SX * 0.664),
                                      int(self.SY * 0.965), int(self.SX * 0.003), int(self.SY * 0.031), tk.NW)

        self.CanvasMenu2 = CanvasMenu(self.CanvasFrmFond, 'Media/FrmAjout/Menu/', int(self.SX * 0.331),
                                      int(self.SY * 0.965), int(self.SX * 0.998), int(self.SY * 0.031), tk.NE)

        self.CanvasFrmFond.focus_set()
        self.CanvasFrmFond.bind('<Motion>', self.MoveOnCanvas)
        self.CanvasFrmFond.bind('<Button-1>', self.ClicOnCanvas)

        self.CanvasFrmFond.pack()

        self.ListChampsTabPlanningTP = 'DATE, TYPE, HDEB , HFIN, CLASSE, NGROUPES, TITRE'
        self.ListChampsTabPlanningNote = 'DATE, TYPE, TITRE'
        Type = ''
        if self.MainAppli.BaseEnCours == "CHIMIE":
            self.MainAppli.cur.execute("select " + self.ListChampsTabPlanningTP +
                                       " from PlanningTPChimie WHERE TYPE='TP' order by DATE")
            self.ListTPinPlanning = self.MainAppli.cur.fetchall()
            Type = 'chimie'
            self.MainAppli.cur.execute("select " + self.ListChampsTabPlanningNote +
                                       " from PlanningTPChimie WHERE TYPE='NOTE' order by DATE")
            self.ListNoteinPlanning = self.MainAppli.cur.fetchall()
        elif self.MainAppli.BaseEnCours == "PHYS":
            self.MainAppli.curphys.execute("select " + self.ListChampsTabPlanningTP +
                                           " from PlanningTPPhys WHERE TYPE='TP' order by DATE")
            self.ListTPinPlanning = self.MainAppli.curphys.fetchall()
            self.MainAppli.curphys.execute("select " + self.ListChampsTabPlanningNote +
                                           " from PlanningTPPhys WHERE TYPE='NOTE' order by DATE")
            self.ListNoteinPlanning = self.MainAppli.curphys.fetchall()
            Type = 'physique'

        self.LabelTag = LabelInCanvas(self.CanvasFrmFond, 'Planning des travaux pratiques de ' + Type, '#E0E0E0',
                                      AppliFont('Helvetica', self.MainAppli.SizeFont, 'normal', 0),
                                      int(self.SX * 0.005), int(self.SY * coefY), tk.NW)
        self.AffichPlanning()
        self.AffichSelectTP()

    def AffichPlanning(self):
        LabelTagMenu1 = LabelInCanvas(self.CanvasMenu1.CanvasMenu, "Sélection d'une date", '#E0E0E0',
                                      AppliFont('Helvetica', self.MainAppli.SizeFont, 'bold', 0),
                                      int(int(self.CanvasMenu1.CanvasMenu['width']) * 0.01),
                                      int(int(self.CanvasMenu1.CanvasMenu['height']) * 0.004), tk.NW)
        LabelTagMenu1.Label.bind('<Button-1>', self.ClicOnCanvas)
        self.CanvasMenu1.CanvasMenu.bind('<Button-1>', self.ClicOnCanvas)

        self.FrmAgenda = FrmAgenda(self.CanvasFrmFond, self)
        ListDateNote = []
        ListNote = []
        if len(self.ListNoteinPlanning) > 0:
            for i in range(len(self.ListNoteinPlanning)):
                Date = self.ListNoteinPlanning[i][0].split(' ')
                An = Date[-1]
                Mois = ConvertMois(Date[-2])
                Jour = Date[-3]
                Date = An + '-' + str(Mois) + '-' + Jour
                Date = datetime.datetime.strptime(Date, "%Y-%m-%d")
                if Date not in ListDateNote:
                    ListDateNote.append(Date)
                    ListNote.append(self.ListNoteinPlanning[i][2])
        ListDate = []
        if len(self.ListTPinPlanning) > 0:
            for i in range(len(self.ListTPinPlanning)):
                Date = self.ListTPinPlanning[i][0].split(' ')
                An = Date[-1]
                Mois = ConvertMois(Date[-2])
                Jour = Date[-3]
                Date = An + '-' + str(Mois) + '-' + Jour
                Date = datetime.datetime.strptime(Date, "%Y-%m-%d")
                if Date not in ListDate:
                    if Date in ListDateNote:
                        self.FrmAgenda.Agenda.EffaceEvent(Date)
                    self.AffichTPOnPlanning(Date, self.MainAppli.BaseEnCours, self.ListTPinPlanning[i][4],
                                            self.ListTPinPlanning[i][6], self.ListTPinPlanning[i][5],
                                            self.ListTPinPlanning[i][2], self.ListTPinPlanning[i][3])
                    ListDate.append(Date)
        if len(ListDateNote) > 0:
            for i in range(len(ListDateNote)):
                if ListDateNote[i] not in ListDate:
                    self.AffichNoteOnPlanning(ListDateNote[i], ListNote[i])

        self.FrmAgenda.Agenda.selection_set(self.FrmAgenda.Agenda.datetime.today())

    def AffichSelectTP(self):
        self.EffaceMenu2()
        self.BtnPostit = BtnAction(self.CanvasMenu2.CanvasMenu, int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.96),
                                   int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.05), self.RatioX,
                                   self.RatioX, 'Media/Divers/BtnNote/')
        self.BtnPostit.CanvasBtn.bind('<ButtonRelease-1>', self.AjoutNote)
        self.DateLabel = LabelInCanvas(self.CanvasMenu2.CanvasMenu, "", '#E0E0E0',
                                       AppliFont('Helvetica', self.MainAppli.SizeFont + 2, 'bold', 1),
                                       int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.5),
                                       int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.08), tk.CENTER)
        self.DateLabel.Label['text'] = self.FrmAgenda.DateSelected
        self.DateLabel.Label.bind('<Button-1>', self.ClicOnCanvas)

        self.TitreClasse = self.CanvasMenu2.CanvasMenu.create_text(
            int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.05),
            int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.16), text='Classe :',
            font=AppliFont('Helvetica', self.MainAppli.SizeFont + 1, 'bold', 0), anchor=tk.W)

        self.Classe.set('')
        self.ListeClasse = ListeDeroulante(self.CanvasMenu2.CanvasMenu,
                                           int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.02),
                                           textvariable=self.Classe, values=self.ClasseListe)
        self.CanvasMenu2.CanvasMenu.create_window(int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.15),
                                                  int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.16),
                                                  anchor=tk.W, window=self.ListeClasse)
        self.ListeClasse.bind('<<ComboboxSelected>>', self.AffichTPClasse)

        self.TitreNbrGr = self.CanvasMenu2.CanvasMenu.create_text(
            int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.05),
            int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.2), text='Nombre de groupes :',
            font=AppliFont('Helvetica', self.MainAppli.SizeFont + 1, 'bold', 0), anchor=tk.W)

        self.NbrGr.set('')
        self.ListeNbrGr = ListeDeroulante(self.CanvasMenu2.CanvasMenu,
                                          int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.005),
                                          textvariable=self.NbrGr, values=self.NbrGrListe)
        self.CanvasMenu2.CanvasMenu.create_window(int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.30),
                                                  int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.2),
                                                  anchor=tk.W, window=self.ListeNbrGr)

        self.TitreHoraire = self.CanvasMenu2.CanvasMenu.create_text(
            int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.5),
            int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.16), text='Horaires :',
            font=AppliFont('Helvetica', self.MainAppli.SizeFont + 1, 'bold', 0), anchor=tk.W)
        self.LabelHDeb = LabelInCanvas(self.CanvasMenu2.CanvasMenu, '8', '#E0E0E0',
                                       AppliFont('Helvetica', self.MainAppli.SizeFont + 4, 'bold', 0),
                                       int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.675),
                                       int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.16), tk.E)
        ChangeCursor(self.LabelHDeb.Label)
        self.LabelHDeb.Label.bind('<MouseWheel>', self.MouseWheelLabelHDeb)
        self.LabelHDeb.Label.bind('<Button-1>', self.ClicOnCanvas)
        self.LabelHDeb.Label.config(relief='raised')
        self.TextHDeb = self.CanvasMenu2.CanvasMenu.create_text(
            int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.677),
            int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.16), text=' H ',
            font=AppliFont('Helvetica', self.MainAppli.SizeFont + 1, 'bold', 0), anchor=tk.W)
        self.LabelMinDeb = LabelInCanvas(self.CanvasMenu2.CanvasMenu, '00', '#E0E0E0',
                                         AppliFont('Helvetica', self.MainAppli.SizeFont + 4, 'bold', 0),
                                         int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.71),
                                         int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.16), tk.W)
        self.LabelMinDeb.Label.bind('<MouseWheel>', self.MouseWheelLabelMinDeb)
        self.LabelMinDeb.Label.bind('<Button-1>', self.ClicOnCanvas)
        ChangeCursor(self.LabelMinDeb.Label)
        self.LabelMinDeb.Label.config(relief='raised')

        self.TextTiret = self.CanvasMenu2.CanvasMenu.create_text(
            int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.76),
            int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.16), text=' - ',
            font=AppliFont('Helvetica', self.MainAppli.SizeFont + 2, 'bold', 0), anchor=tk.W)
        self.LabelHFin = LabelInCanvas(self.CanvasMenu2.CanvasMenu, '9', '#E0E0E0',
                                       AppliFont('Helvetica', self.MainAppli.SizeFont + 4, 'bold', 0),
                                       int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.835),
                                       int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.16), tk.E)
        ChangeCursor(self.LabelHFin.Label)
        self.LabelHFin.Label.bind('<MouseWheel>', self.MouseWheelLabelHFin)
        self.LabelHFin.Label.bind('<Button-1>', self.ClicOnCanvas)
        self.LabelHFin.Label.config(relief='raised')
        self.TextHFin = self.CanvasMenu2.CanvasMenu.create_text(
            int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.837),
            int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.16), text=' H ',
            font=AppliFont('Helvetica', self.MainAppli.SizeFont + 2, 'bold', 0), anchor=tk.W)
        self.LabelMinFin = LabelInCanvas(self.CanvasMenu2.CanvasMenu, '00', '#E0E0E0',
                                         AppliFont('Helvetica', self.MainAppli.SizeFont + 4, 'bold', 0),
                                         int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.87),
                                         int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.16), tk.W)
        self.LabelMinFin.Label.bind('<MouseWheel>', self.MouseWheelLabelMinFin)
        self.LabelMinFin.Label.bind('<Button-1>', self.ClicOnCanvas)
        ChangeCursor(self.LabelMinFin.Label)
        self.LabelMinFin.Label.config(relief='raised')

        LabelInCanvas(self.CanvasMenu2.CanvasMenu, 'TRAVAUX PRATIQUES', '#E0E0E0',
                      AppliFont('Helvetica', self.MainAppli.SizeFont + 2, 'bold', 1),
                      int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.01),
                      int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.28), tk.W)

        self.EntryTP = EntryData(self.CanvasMenu2.CanvasMenu, int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.108),
                                 int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.5),
                                 int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.33), tk.CENTER,
                                 AppliFont('Helvetica', self.MainAppli.SizeFont + 2, 'bold', 0))

        self.EntryTP.EntryData.config(justify='center')
        self.EntryTP.EntryData.bind('<KeyRelease>', self.ModifTP)

        self.ListBoxTP = Scrollable_ListBox(self.CanvasMenu2.CanvasMenu,
                                            int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.01),
                                            int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.37),
                                            int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.158),
                                            int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.032))

        self.ListBoxTP.ListBox.bind('<<ListboxSelect>>', self.OnSelectListBox)

        self.AffichListTP()

        self.BtnOK = BtnAction(self.CanvasMenu2.CanvasMenu, int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.88),
                               int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.95), self.RatioX * 0.75,
                               self.RatioX * 0.75, 'Media/FrmAjout/BtnOK2/')
        self.BtnOK.CanvasBtn.bind('<ButtonRelease-1>', self.ValidAjoutTP)
        self.BtnAnnul = BtnAction(self.CanvasMenu2.CanvasMenu, int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.95),
                                  int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.95), self.RatioX * 0.75,
                                  self.RatioX * 0.75, 'Media/FrmAjout/BtnAnnul2/')
        self.BtnAnnul.CanvasBtn.bind('<ButtonRelease-1>', self.AnnulAjoutTP)
        self.BtnCopier = BtnAction(self.CanvasMenu2.CanvasMenu, int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.05),
                                   int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.055), self.RatioX * 0.2,
                                   self.RatioX * 0.2, 'Media/FrmTP/BtnCopier/')
        self.BtnCopier.CanvasBtn.bind('<ButtonRelease-1>', self.CopieTP)

        self.CanvasMenu2.CanvasMenu.bind('<Button-1>', self.ClicOnCanvas)
        self.ListeClasse.bind('<FocusIn>', self.ClicOnCanvas)
        self.ListeNbrGr.bind('<FocusIn>', self.ClicOnCanvas)
        self.EntryTP.EntryData.bind('<FocusIn>', self.ClicOnCanvas)

        Type = ''
        if self.MainAppli.BaseEnCours == "CHIMIE":
            Type = 'CHIMIE'
        elif self.MainAppli.BaseEnCours == "PHYS":
            Type = 'PHYSIQUE'

        self.DeterminListTPDate()
        self.DeterminListNoteDate()

        if len(self.ListTPDate) > 0:
            if not self.AjoutNewTP:
                Titre = "Modifier un TP de " + Type + " au planning pour la date sélectionnée"
                self.EntryTP.Data.set(self.ListTPDate[self.IndexTP][6])
                self.ActionModifTP()
                self.Classe.set(self.ListTPDate[self.IndexTP][4])
                self.NbrGr.set(self.ListTPDate[self.IndexTP][5])
                hdeb = int(divmod(float(self.ListTPDate[self.IndexTP][2]) * 60, 60)[0])
                mindeb = int(round(divmod(float(self.ListTPDate[self.IndexTP][2]) * 60, 60)[1] / 5) * 5)
                hfin = int(divmod(float(self.ListTPDate[self.IndexTP][3]) * 60, 60)[0])
                minfin = int(round(divmod(float(self.ListTPDate[self.IndexTP][3]) * 60, 60)[1] / 5) * 5)
                self.LabelHDeb.Label['text'] = str(hdeb)
                self.LabelHFin.Label['text'] = str(hfin)
                self.LabelMinDeb.Label['text'] = str(mindeb).zfill(2)
                self.LabelMinFin.Label['text'] = str(minfin).zfill(2)

                self.BtnPlus = BtnAction(self.CanvasMenu2.CanvasMenu,
                                         int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.978),
                                         int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.0134), self.RatioX * 0.52,
                                         self.RatioX * 0.52, 'Media/FrmConsomProd/BtnPlus/')
                self.BtnPlus.CanvasBtn.bind('<ButtonRelease-1>', self.NewTP)

                if len(self.ListTPDate) > 1:
                    self.BtnSuiv = BtnAction(self.CanvasMenu2.CanvasMenu,
                                             int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.94),
                                             int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.015),
                                             self.RatioX, self.RatioY, 'Media/FrmMain/BtnSuiv2/')
                    ChangeCursor(self.BtnSuiv.CanvasBtn)
                    self.BtnSuiv.CanvasBtn.bind('<ButtonRelease-1>', self.AffichTPSuiv)
            else:
                Titre = "Ajouter un nouveau TP de " + Type + " au planning pour la date sélectionnée"
                self.EntryTP.Data.set('')
                self.Classe.set('')
                self.NbrGr.set('')
                self.LabelHDeb.Label['text'] = str(8)
                self.LabelHFin.Label['text'] = str(9)
                self.LabelMinDeb.Label['text'] = str(0).zfill(2)
                self.LabelMinFin.Label['text'] = str(0).zfill(2)
        else:
            Titre = "Ajouter un TP de " + Type + " au planning pour la date sélectionnée"

        LabelInCanvas(self.CanvasMenu2.CanvasMenu, Titre, '#E0E0E0',
                      AppliFont('Helvetica', self.MainAppli.SizeFont, 'bold', 0),
                      int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.01),
                      int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.004), tk.NW)

    def MouseWheelLabelHDeb(self, event):
        if event.delta == -120:
            if int(self.LabelHDeb.Label['text']) > 8:
                self.LabelHDeb.Label['text'] = int(self.LabelHDeb.Label['text']) - 1
        if event.delta == 120:
            if int(self.LabelHDeb.Label['text']) < 17:
                self.LabelHDeb.Label['text'] = int(self.LabelHDeb.Label['text']) + 1
                if int(self.LabelHFin.Label['text']) - 1 < int(self.LabelHDeb.Label['text']):
                    if int(self.LabelHFin.Label['text']) < 18:
                        self.LabelHFin.Label['text'] = int(self.LabelHFin.Label['text']) + 1

    def MouseWheelLabelHFin(self, event):
        if event.delta == -120:
            if int(self.LabelHFin.Label['text']) > 9:
                self.LabelHFin.Label['text'] = int(self.LabelHFin.Label['text']) - 1
                if int(self.LabelHFin.Label['text']) < int(self.LabelHDeb.Label['text']) + 1:
                    if int(self.LabelHDeb.Label['text']) > 8:
                        self.LabelHDeb.Label['text'] = int(self.LabelHDeb.Label['text']) - 1
        if event.delta == 120:
            if int(self.LabelHFin.Label['text']) < 18:
                self.LabelHFin.Label['text'] = int(self.LabelHFin.Label['text']) + 1

    def MouseWheelLabelMinFin(self, event):
        if event.delta == -120:
            if int(self.LabelMinFin.Label['text']) > 0:
                self.LabelMinFin.Label['text'] = str(int(self.LabelMinFin.Label['text']) - 5).zfill(2)
        if event.delta == 120:
            if int(self.LabelMinFin.Label['text']) < 55:
                self.LabelMinFin.Label['text'] = str(int(self.LabelMinFin.Label['text']) + 5).zfill(2)
            else:
                self.LabelMinFin.Label['text'] = '00'

    def MouseWheelLabelMinDeb(self, event):
        if event.delta == -120:
            if int(self.LabelMinDeb.Label['text']) > 0:
                self.LabelMinDeb.Label['text'] = str(int(self.LabelMinDeb.Label['text']) - 5).zfill(2)
        if event.delta == 120:
            if int(self.LabelMinDeb.Label['text']) < 55:
                self.LabelMinDeb.Label['text'] = str(int(self.LabelMinDeb.Label['text']) + 5).zfill(2)
            else:
                self.LabelMinDeb.Label['text'] = '00'

    def DeterminListTPDate(self):
        ListTPDate = []
        if self.MainAppli.BaseEnCours == "CHIMIE":
            self.MainAppli.cur.execute("select " + self.ListChampsTabPlanningTP +
                                       " from PlanningTPChimie WHERE TYPE='TP' order by DATE")
            ListTPDate = self.MainAppli.cur.fetchall()

        elif self.MainAppli.BaseEnCours == "PHYS":
            self.MainAppli.curphys.execute("select " + self.ListChampsTabPlanningTP +
                                           " from PlanningTPPhys WHERE TYPE='TP' order by DATE")
            ListTPDate = self.MainAppli.curphys.fetchall()
        self.ListTPDate = []
        for i in range(len(ListTPDate)):
            Date = self.DateLabel.Label['text'].split(' ')
            if ListTPDate[i][0] == self.DateLabel.Label['text'] or \
                    ListTPDate[i][0] == ' '.join([Date[i] for i in range(1, 4)]) or \
                    ListTPDate[i][0] == '0' + ' '.join([Date[i] for i in range(1, 4)]):
                self.ListTPDate.append(ListTPDate[i])

    def DeterminListNoteDate(self):
        ListNoteDate = []
        if self.MainAppli.BaseEnCours == "CHIMIE":
            self.MainAppli.cur.execute("select " + self.ListChampsTabPlanningNote +
                                       " from PlanningTPChimie WHERE TYPE='NOTE' order by DATE")
            ListNoteDate = self.MainAppli.cur.fetchall()

        elif self.MainAppli.BaseEnCours == "PHYS":
            self.MainAppli.curphys.execute("select " + self.ListChampsTabPlanningNote +
                                           " from PlanningTPPhys WHERE TYPE='NOTE' order by DATE")
            ListNoteDate = self.MainAppli.curphys.fetchall()
        self.ListNoteDate = []
        for i in range(len(ListNoteDate)):
            Date = self.DateLabel.Label['text'].split(' ')
            if ListNoteDate[i][0] == self.DateLabel.Label['text'] or \
                    ListNoteDate[i][0] == ' '.join([Date[i] for i in range(1, 4)]) or \
                    ListNoteDate[i][0] == '0' + ' '.join([Date[i] for i in range(1, 4)]):
                self.ListNoteDate.append(ListNoteDate[i])

        if len(self.ListNoteDate) > 0:
            self.BtnPostit.CanvasBtn.itemconfig(self.BtnPostit.ImgCanvasBtn, image=self.BtnPostit.ImgBtn[2])
        else:
            self.BtnPostit.CanvasBtn.itemconfig(self.BtnPostit.ImgCanvasBtn, image=self.BtnPostit.ImgBtn[0])

    def AffichListTP(self):
        self.ListTP = []
        if self.MainAppli.BaseEnCours == "CHIMIE":
            self.MainAppli.cur.execute("select TITRE from TP order by TITRE")
            self.ListTPs = self.MainAppli.cur.fetchall()
        elif self.MainAppli.BaseEnCours == "PHYS":
            self.MainAppli.curphys.execute("select TITRE from TP order by TITRE")
            self.ListTPs = self.MainAppli.curphys.fetchall()

        for i in range(len(self.ListTPs)):
            if self.ListTPs[i][0] not in self.ListTP:
                self.ListTP.append(self.ListTPs[i][0])

        self.ListBoxTP.ListBox.delete(0, tk.END)
        for i in range(len(self.ListTP)):
            self.ListBoxTP.ListBox.insert(tk.END, self.ListTP[i])

    def AffichTPClasse(self, _):
        self.ListTP = []
        if self.MainAppli.BaseEnCours == "CHIMIE":
            self.MainAppli.cur.execute("select TITRE from TP WHERE CLASSE=\"" + self.Classe.get() + "\"order by TITRE")
            self.ListTPs = self.MainAppli.cur.fetchall()
        if self.MainAppli.BaseEnCours == "PHYS":
            self.MainAppli.curphys.execute("select TITRE from TP WHERE CLASSE=\"" + self.Classe.get() +
                                           "\"order by TITRE")
            self.ListTPs = self.MainAppli.curphys.fetchall()

        for i in range(len(self.ListTPs)):
            if self.ListTPs[i][0] not in self.ListTP:
                self.ListTP.append(self.ListTPs[i][0])

        self.ListBoxTP.ListBox.delete(0, tk.END)
        for i in range(len(self.ListTP)):
            self.ListBoxTP.ListBox.insert(tk.END, self.ListTP[i])

    def ModifTP(self, _):
        self.ActionModifTP()

    def ActionModifTP(self):
        self.ListTP = []
        if self.MainAppli.BaseEnCours == "CHIMIE":
            try:
                self.MainAppli.cur.execute("SELECT TITRE, CLASSE FROM TP WHERE TITRE LIKE \"%" +
                                           self.EntryTP.Data.get() + "%\" AND CLASSE=\"" + self.Classe.get() +
                                           "\" order by TITRE")
                self.ListTPs = self.MainAppli.cur.fetchall()
            except:
                self.MainAppli.cur.execute("SELECT TITRE, CLASSE FROM TP WHERE TITRE LIKE \"%" +
                                           self.EntryTP.Data.get().split(' ')[0] + "%\" AND CLASSE=\"" +
                                           self.Classe.get() + "\" order by TITRE")
                self.ListTPs = self.MainAppli.cur.fetchall()

        elif self.MainAppli.BaseEnCours == "PHYS":
            try:
                self.MainAppli.curphys.execute("SELECT TITRE, CLASSE FROM TP WHERE TITRE LIKE \"%" +
                                               self.EntryTP.Data.get() + "%\" AND CLASSE=\"" + self.Classe.get() +
                                               "\" order by TITRE")
                self.ListTPs = self.MainAppli.curphys.fetchall()
            except:
                self.MainAppli.curphys.execute("SELECT TITRE, CLASSE FROM TP WHERE TITRE LIKE \"%" +
                                               self.EntryTP.Data.get().split(' ')[0] + "%\" AND CLASSE=\"" +
                                               self.Classe.get() + "\" order by TITRE")
                self.ListTPs = self.MainAppli.curphys.fetchall()

        for i in range(len(self.ListTPs)):
            if self.ListTPs[i][0] not in self.ListTP:
                self.ListTP.append(self.ListTPs[i][0])

        self.ListBoxTP.ListBox.delete(0, tk.END)
        for i in range(len(self.ListTP)):
            self.ListBoxTP.ListBox.insert(tk.END, self.ListTP[i])
        self.ListBoxTP.ListBox.selection_set(0)

    def OnSelectListBox(self, evt):
        self.FrmAgenda.lift()
        try:
            w = evt.widget
            IndexElt = int(w.curselection()[0])
            self.EntryTP.Data.set(self.ListTP[IndexElt])
            if self.MainAppli.BaseEnCours == "CHIMIE":
                self.Classe.set(ChercheClasseTP(self.MainAppli.cur, self.ListTP[IndexElt]))
            elif self.MainAppli.BaseEnCours == "PHYS":
                self.Classe.set(ChercheClasseTP(self.MainAppli.curphys, self.ListTP[IndexElt]))
        except:
            pass

    def NewTP(self, _):
        self.FrmAgenda.lift()
        self.AjoutNewTP = True
        self.AffichSelectTP()

    def CopieTP(self, _):
        self.BtnCopier.CanvasBtn.itemconfig(self.BtnCopier.ImgCanvasBtn, image=self.BtnCopier.ImgBtn[0])
        self.FrmAgenda.lift()
        if not self.ActionCopieTP:
            self.ListCopieTP = []
            HDEB = round((int(self.LabelHDeb.Label['text']) * 60 + int(self.LabelMinDeb.Label['text'])) / 60, 2)
            HFIN = round((int(self.LabelHFin.Label['text']) * 60 + int(self.LabelMinFin.Label['text'])) / 60, 2)
            self.ListCopieTP.append((self.EntryTP.Data.get(), HDEB, HFIN, self.Classe.get(), self.NbrGr.get()))
            self.ActionCopieTP = True
        else:
            self.EntryTP.Data.set(self.ListCopieTP[0][0])
            hdeb = int(divmod(float(self.ListCopieTP[0][1]) * 60, 60)[0])
            mindeb = int(round(divmod(float(self.ListCopieTP[0][1]) * 60, 60)[1] / 5) * 5)
            hfin = int(divmod(float(self.ListCopieTP[0][2]) * 60, 60)[0])
            minfin = int(round(divmod(float(self.ListCopieTP[0][2]) * 60, 60)[1] / 5) * 5)
            self.LabelHDeb.Label['text'] = str(hdeb)
            self.LabelHFin.Label['text'] = str(hfin)
            self.LabelMinDeb.Label['text'] = str(mindeb).zfill(2)
            self.LabelMinFin.Label['text'] = str(minfin).zfill(2)
            self.Classe.set(self.ListCopieTP[0][3])
            self.NbrGr.set(self.ListCopieTP[0][4])
            self.ModifTP(_)
            self.ActionCopieTP = False

    def ValidAjoutTP(self, _):
        self.BtnOK.CanvasBtn.itemconfig(self.BtnOK.ImgCanvasBtn, image=self.BtnOK.ImgBtn[0])
        self.FrmAgenda.lift()
        TP = self.EntryTP.Data.get()
        if TP != '' and self.NbrGr.get() != '' and self.Classe.get() != '':
            HDEB = round((int(self.LabelHDeb.Label['text']) * 60 + int(self.LabelMinDeb.Label['text'])) / 60, 2)
            HFIN = round((int(self.LabelHFin.Label['text']) * 60 + int(self.LabelMinFin.Label['text'])) / 60, 2)
            if len(self.ListTPDate) > 0 and not self.AjoutNewTP:
                self.FrmAgenda.Agenda.EffaceEvent(self.FrmAgenda.Agenda.selection_get())
                if self.MainAppli.BaseEnCours == "CHIMIE":
                    try:
                        self.MainAppli.cur.execute("DELETE FROM PlanningTPChimie WHERE TITRE=\"" +
                                                   self.EntryTP.Data.get() + "\" and DATE =\"" +
                                                   self.DateLabel.Label['text'] + "\"")
                    except:
                        self.MainAppli.cur.execute("DELETE FROM PlanningTPChimie WHERE DATE =\"" +
                                                   self.DateLabel.Label['text'] + "\"")
                    self.MainAppli.DataBaseChimie.commit()
                elif self.MainAppli.BaseEnCours == "PHYS":
                    try:
                        self.MainAppli.curphys.execute("DELETE FROM PlanningTPPhys WHERE TITRE=\"" +
                                                       self.EntryTP.Data.get() + "\" and DATE =\"" +
                                                       self.DateLabel.Label['text'] + "\"")
                    except:
                        self.MainAppli.curphys.execute("DELETE FROM PlanningTPPhys WHERE DATE =\"" +
                                                       self.DateLabel.Label['text'] + "\"")
                    self.MainAppli.DataBasePhys.commit()
            elif len(self.ListTPDate) > 0 and self.AjoutNewTP:
                self.FrmAgenda.Agenda.EffaceEvent(self.FrmAgenda.Agenda.selection_get())
            data = [(self.FrmAgenda.DateSelected, 'TP', HDEB, HFIN, self.Classe.get(), self.NbrGr.get(),
                     self.EntryTP.Data.get())]
            if self.MainAppli.BaseEnCours == "CHIMIE":
                self.MainAppli.cur.execute("INSERT INTO PlanningTPChimie (DATE, TYPE, HDEB , HFIN, CLASSE, "
                                           "NGROUPES, TITRE) VALUES(?,?,?,?,?,?,?)", data[0])
                self.MainAppli.DataBaseChimie.commit()
                self.MainAppli.SaveListModifDTB('Chimie', 'Ajout TP - ' + self.EntryTP.Data.get() + ' (' +
                                                self.FrmAgenda.DateSelected + ')')
            elif self.MainAppli.BaseEnCours == "PHYS":
                self.MainAppli.curphys.execute("INSERT INTO PlanningTPPhys (DATE, TYPE, HDEB , HFIN, CLASSE, "
                                               "NGROUPES, TITRE) VALUES(?,?,?,?,?,?,?)", data[0])
                self.MainAppli.DataBasePhys.commit()
                self.MainAppli.SaveListModifDTB('Physique', 'Ajout TP - ' + self.EntryTP.Data.get() + ' (' +
                                                self.FrmAgenda.DateSelected + ')')

            self.DeterminListNoteDate()
            if len(self.ListNoteDate) > 0:
                self.FrmAgenda.Agenda.EffaceEvent(self.FrmAgenda.Agenda.selection_get())
            self.AffichTPOnPlanning(self.FrmAgenda.Agenda.selection_get(), self.MainAppli.BaseEnCours,
                                    self.Classe.get(), TP, self.NbrGr.get(), HDEB, HFIN)
            self.ModifTP(_)
            self.DeterminListTPDate()
            TitreTP = []
            for i in range(len(self.ListTPDate)):
                TitreTP.append(self.ListTPDate[i][6])

            if self.AjoutNewTP:
                self.AjoutNewTP = False

            self.IndexTP = TitreTP.index(self.EntryTP.Data.get())
            self.AffichSelectTP()
        else:
            tkMB.showwarning('Attention',
                             "Veuillez indiquer le titre, la classe, le nombre de groupes et les horaires du TP!",
                             parent=self.FrmAgenda)
            self.FrmAgenda.lift()

    def AnnulAjoutTP(self, _):
        self.BtnAnnul.CanvasBtn.itemconfig(self.BtnAnnul.ImgCanvasBtn, image=self.BtnAnnul.ImgBtn[0])
        if len(self.ListTPDate) > 0 and not self.AjoutNewTP:
            Rep = tkMB.askyesno('Attention', 'Voulez-vous supprimer le TP "' + self.EntryTP.Data.get() + '" du ' +
                                self.DateLabel.Label['text'] + '?', parent=self.FrmAgenda)
            if Rep:
                self.FrmAgenda.lift()
                if self.MainAppli.BaseEnCours == "CHIMIE":
                    try:
                        self.MainAppli.cur.execute("DELETE FROM PlanningTPChimie WHERE TITRE=\"" +
                                                   self.EntryTP.Data.get() + "\" and DATE =\"" +
                                                   self.DateLabel.Label['text'] + "\"")
                    except:
                        self.MainAppli.cur.execute("DELETE FROM PlanningTPChimie WHERE DATE =\"" +
                                                   self.DateLabel.Label['text'] + "\"")
                    self.MainAppli.DataBaseChimie.commit()
                    self.MainAppli.SaveListModifDTB('Chimie', 'Suppression TP - ' + self.EntryTP.Data.get() + ' (' +
                                                    self.DateLabel.Label['text'] + ')')
                elif self.MainAppli.BaseEnCours == "PHYS":
                    try:
                        self.MainAppli.curphys.execute("DELETE FROM PlanningTPPhys WHERE TITRE=\"" +
                                                       self.EntryTP.Data.get() + "\" and DATE =\"" +
                                                       self.DateLabel.Label['text'] + "\"")
                    except:
                        self.MainAppli.curphys.execute("DELETE FROM PlanningTPPhys WHERE DATE =\"" +
                                                       self.DateLabel.Label['text'] + "\"")
                    self.MainAppli.DataBasePhys.commit()
                    self.MainAppli.SaveListModifDTB('Physique', 'Suppression TP - ' + self.EntryTP.Data.get() + ' (' +
                                                    self.DateLabel.Label['text'] + ')')
                self.FrmAgenda.Agenda.EffaceEvent(self.FrmAgenda.Agenda.selection_get())
                self.AffichListTP()
                self.DeterminListTPDate()
                self.DeterminListNoteDate()
                if len(self.ListTPDate) == 0 and len(self.ListNoteDate) > 0:
                    self.AffichNoteOnPlanning(self.FrmAgenda.Agenda.selection_get(), self.ListNoteDate[0][2])
                self.IndexTP = 0
                self.AffichSelectTP()
                if len(self.ListTPDate) > 0:
                    HDEB = round((int(self.LabelHDeb.Label['text']) * 60 + int(self.LabelMinDeb.Label['text'])) / 60, 2)
                    HFIN = round((int(self.LabelHFin.Label['text']) * 60 + int(self.LabelMinFin.Label['text'])) / 60, 2)
                    self.AffichTPOnPlanning(self.FrmAgenda.Agenda.selection_get(), self.MainAppli.BaseEnCours,
                                            self.Classe.get(), self.EntryTP.Data.get(), self.NbrGr.get(), HDEB, HFIN)

            else:
                self.FrmAgenda.lift()
        elif len(self.ListTPDate) > 0 and self.AjoutNewTP:
            self.AjoutNewTP = False
            self.AffichSelectTP()
        else:
            self.FrmAgenda.lift()
            self.EntryTP.Data.set('')
            self.Classe.set('')
            self.NbrGr.set('')
            self.AffichListTP()

    def ActionMouseWheelOnLabel(self, _):
        if len(self.ListTPDate) > 1 or (len(self.ListTPDate) == 1 and len(self.ListNoteDate) > 0):
            self.AffichTPSuiv(_)

    def AffichTPSuiv(self, _):
        self.FrmAgenda.lift()
        if self.IndexTP < len(self.ListTPDate) - 1 and not self.AffichNote:
            self.IndexTP = self.IndexTP + 1
        elif not self.AffichNote:
            if len(self.ListNoteDate) > 0:
                self.AffichNote = True
                self.AffichNoteOnPlanning(self.FrmAgenda.Agenda.selection_get(), self.ListNoteDate[0][2])
            self.IndexTP = 0
        elif self.AffichNote:
            self.AffichNote = False
            self.IndexTP = 0
        self.AffichSelectTP()
        if not self.AffichNote:
            self.FrmAgenda.Agenda.EffaceEvent(self.FrmAgenda.Agenda.selection_get())
            HDEB = round((int(self.LabelHDeb.Label['text']) * 60 + int(self.LabelMinDeb.Label['text'])) / 60, 2)
            HFIN = round((int(self.LabelHFin.Label['text']) * 60 + int(self.LabelMinFin.Label['text'])) / 60, 2)
            self.AffichTPOnPlanning(self.FrmAgenda.Agenda.selection_get(), self.MainAppli.BaseEnCours,
                                    self.Classe.get(), self.EntryTP.Data.get(), self.NbrGr.get(), HDEB, HFIN)

    def AffichTPOnPlanning(self, Date, Type, Classe, TP, NbrGr, HDEB, HFIN):
        ListRemind = ['\nTP ' + Type + ' ' + Classe]
        TP = FormatTP(TP)
        ListRemind.append('\n' + TP)
        hdeb = int(divmod(float(HDEB) * 60, 60)[0])
        mindeb = int(round(divmod(float(HDEB) * 60, 60)[1] / 5) * 5)
        hfin = int(divmod(float(HFIN) * 60, 60)[0])
        minfin = int(round(divmod(float(HFIN) * 60, 60)[1] / 5) * 5)
        if int(NbrGr) > 1:
            ListRemind.append('\n(' + NbrGr + ' groupes / ' + str(hdeb) + 'H' + str(mindeb).zfill(2) + ' - ' +
                              str(hfin) + 'H' + str(minfin).zfill(2) + ')')
        else:
            ListRemind.append('\n(' + NbrGr + ' groupe/ ' + str(hdeb) + 'H' + str(mindeb).zfill(2) + ' - ' +
                              str(hfin) + 'H' + str(minfin).zfill(2) + ')')

        for i in range(len(ListRemind)):
            self.FrmAgenda.Agenda.calevent_create(Date, ListRemind[i], 'reminder')

    def AffichNoteOnPlanning(self, Date, TextNote):
        self.FrmAgenda.Agenda.EffaceEvent(Date)
        self.FrmAgenda.Agenda.calevent_create(Date, '\n' + TextNote, 'reminder')

    def AffichPlanningJour(self):
        self.FrmAgenda.lower()
        self.EffaceMenu1()
        LabelInCanvas(self.CanvasMenu1.CanvasMenu, self.FrmAgenda.DateSelected, '#E0E0E0',
                      AppliFont('Helvetica', self.MainAppli.SizeFont + 2, 'bold', 0),
                      int(int(self.CanvasMenu1.CanvasMenu['width']) * 0.5),
                      int(int(self.CanvasMenu1.CanvasMenu['height']) * 0.015), tk.CENTER)

        self.BtnCloseMenu1 = BtnAction(self.CanvasMenu1.CanvasMenu,
                                       int(int(self.CanvasMenu1.CanvasMenu['width']) * 0.985),
                                       int(int(self.CanvasMenu1.CanvasMenu['height']) * 0.014), self.RatioX,
                                       self.RatioY, 'Media/FrmAjout/BtnClose/')
        self.BtnCloseMenu1.CanvasBtn.bind('<ButtonRelease-1>', self.ClosePlanningJour)
        self.BtnCloseMenu1.CanvasBtn.bind('<Motion>', lambda action: self.BtnCloseMenu1.CanvasBtn.itemconfig(
            self.BtnCloseMenu1.ImgCanvasBtn, image=self.BtnCloseMenu1.ImgBtn[1]))
        self.CanvasMenu1.CanvasMenu.bind('<Motion>', self.MoveOnCanvasMenu1)

        self.PlanningJour = PlanningJour(self.CanvasMenu1.CanvasMenu, self.ListTPDate,
                                         AppliFont('Helvetica', self.MainAppli.SizeFont, 'normal', 0), self)

        self.AffichProtocol(self.ListTPDate[0][6])

    def AffichProtocol(self, TP):
        self.EffaceMenu2()
        LabelInCanvas(self.CanvasMenu2.CanvasMenu, 'Protocole du TP sélectionné', '#E0E0E0',
                      AppliFont('Helvetica', self.MainAppli.SizeFont, 'bold', 0),
                      int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.01),
                      int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.004), tk.NW)
        PDF = ''
        Path = ''
        if self.MainAppli.BaseEnCours == "CHIMIE":
            PDF = CherchePDFTP(self.MainAppli.cur, TP)
            Path = 'Datas/PDFTPChim/' + PDF + '.pdf'
        elif self.MainAppli.BaseEnCours == "PHYS":
            PDF = CherchePDFTP(self.MainAppli.curphys, TP)
            Path = 'Datas/PDFTPPhys/' + PDF + '.pdf'

        if PDF != '':
            self.FrmPDF = FrmPDF(self.CanvasMenu2.CanvasMenu, Path, 1.03,
                                 int(self.CanvasMenu2.CanvasMenu['height']),
                                 int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.5),
                                 int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.493),
                                 int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.96),
                                 int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.88))
        else:
            self.NoPDF = NoPDF(self.CanvasMenu2.CanvasMenu, 'Media/FrmInfo/NoPdf/NoPDF.jpg',
                               int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.5),
                               int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.5), self.RatioX, self.RatioY)

    def EffaceMenu1(self):
        for widget in self.CanvasMenu1.CanvasMenu.winfo_children():
            widget.destroy()

    def EffaceMenu2(self):
        for widget in self.CanvasMenu2.CanvasMenu.winfo_children():
            widget.destroy()
        self.CanvasMenu2.CanvasMenu.delete(self.TitreClasse)
        self.CanvasMenu2.CanvasMenu.delete(self.TitreNbrGr)
        self.CanvasMenu2.CanvasMenu.delete(self.TitreHoraire)
        self.CanvasMenu2.CanvasMenu.delete(self.TextHDeb)
        self.CanvasMenu2.CanvasMenu.delete(self.TextTiret)
        self.CanvasMenu2.CanvasMenu.delete(self.TextHFin)

    def AjoutNote(self, _):
        self.FrmAgenda.lift()
        if len(self.ListNoteDate) > 0:
            TextNote = self.ListNoteDate[0][2]
        else:
            TextNote = ''
        self.Note = Note(self.CanvasMenu2.CanvasMenu, 'Media/Divers/FondNote/',
                         int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.34),
                         int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.225),
                         int(int(self.CanvasMenu2.CanvasMenu['width']) * 0.805),
                         int(int(self.CanvasMenu2.CanvasMenu['height']) * 0.15), TextNote, self)

    def SaveNote(self):
        NOcur = 0
        if self.MainAppli.BaseEnCours == "CHIMIE":
            self.MainAppli.cur.execute("Select * from PlanningTPChimie where " + 'TYPE = "NOTE" AND DATE =\"' +
                                       self.DateLabel.Label['text'] + '\"')
            NOcur = len(self.MainAppli.cur.fetchall())
        elif self.MainAppli.BaseEnCours == "PHYS":
            self.MainAppli.curphys.execute("Select * from PlanningTPPhys where " + 'TYPE = "NOTE" AND DATE =\"' +
                                           self.DateLabel.Label['text'] + '\"')
            NOcur = len(self.MainAppli.curphys.fetchall())

        if NOcur > 0:
            if self.MainAppli.BaseEnCours == "CHIMIE":
                SQLRequet = "DELETE FROM PlanningTPChimie WHERE " + 'TYPE = "NOTE" AND DATE =\"' + self.DateLabel.Label[
                    'text'] + '\"'
                self.MainAppli.cur.execute(SQLRequet)
                self.MainAppli.DataBaseChimie.commit()
            elif self.MainAppli.BaseEnCours == "PHYS":
                SQLRequet = "DELETE FROM PlanningTPPhys WHERE " + 'TYPE = "NOTE" AND DATE =\"' + self.DateLabel.Label[
                    'text'] + '\"'
                self.MainAppli.curphys.execute(SQLRequet)
                self.MainAppli.DataBasePhys.commit()

        data = [(self.FrmAgenda.DateSelected, 'NOTE', self.Note.textNote)]
        if self.MainAppli.BaseEnCours == "CHIMIE":
            self.MainAppli.cur.execute("INSERT INTO PlanningTPChimie (DATE, TYPE, TITRE) VALUES(?,?,?)", data[0])
            self.MainAppli.DataBaseChimie.commit()
            self.MainAppli.SaveListModifDTB('Chimie', 'Ajout Note (' + self.FrmAgenda.DateSelected + ')')
        elif self.MainAppli.BaseEnCours == "PHYS":
            self.MainAppli.curphys.execute("INSERT INTO PlanningTPPhys (DATE, TYPE, TITRE) VALUES(?,?,?)", data[0])
            self.MainAppli.DataBasePhys.commit()
            self.MainAppli.SaveListModifDTB('Physique', 'Ajout Note (' + self.FrmAgenda.DateSelected + ')')

        if len(self.ListTPDate) == 0:
            self.AffichNoteOnPlanning(self.FrmAgenda.Agenda.selection_get(), self.Note.textNote)
        self.DeterminListNoteDate()

    def SupNote(self):
        if self.MainAppli.BaseEnCours == "CHIMIE":
            SQLRequet = "DELETE FROM PlanningTPChimie WHERE " + 'TYPE = "NOTE" AND DATE =\"' + self.DateLabel.Label[
                'text'] + '\"'
            self.MainAppli.cur.execute(SQLRequet)
            self.MainAppli.DataBaseChimie.commit()
        elif self.MainAppli.BaseEnCours == "PHYS":
            SQLRequet = "DELETE FROM PlanningTPPhys WHERE " + 'TYPE = "NOTE" AND DATE =\"' + self.DateLabel.Label[
                'text'] + '\"'
            self.MainAppli.curphys.execute(SQLRequet)
            self.MainAppli.DataBasePhys.commit()
        if len(self.ListTPDate) == 0:
            self.FrmAgenda.Agenda.EffaceEvent(self.FrmAgenda.Agenda.selection_get())
        self.DeterminListNoteDate()

    def ClicOnCanvas(self, _):
        self.FrmAgenda.lift()

    def MoveOnCanvas(self, _):
        self.CanvasBtnClose.itemconfig(self.ImgCanvasBtnClose, image=self.ImgBtnClose[0])
        self.MainAppli.CanvasBtnQuit.itemconfig(self.MainAppli.ImgCanvasBtnQuit, image=self.MainAppli.ImgBtnQuit[0])

    def MoveOnCanvasMenu1(self, _):
        if self.BtnCloseMenu1 is not None:
            self.BtnCloseMenu1.CanvasBtn.itemconfig(self.BtnCloseMenu1.ImgCanvasBtn, image=self.BtnCloseMenu1.ImgBtn[0])

    def ClosePlanningJour(self, _):
        self.EffaceMenu1()
        self.BtnCloseMenu1 = None
        self.FrmAgenda.lift()
        self.AffichSelectTP()

    def CacheFrmPlanningTP(self, _):
        self.ActionCacheFrmPlanningTP()

    def ActionCacheFrmPlanningTP(self):
        self.CanvasBtnClose.itemconfig(self.ImgCanvasBtnClose, image=self.ImgBtnClose[0])
        self.destroy()
        self.MainAppli.parent.lift()
        self.MainAppli.Action3()


class FrmAgenda(tk.Toplevel):
    def __init__(self, container, Appli):
        tk.Toplevel.__init__(self, container)
        self.MainAppli = Appli
        self.parent = container
        self.DateSelected = ''

        self.geometry(str(int(int(self.MainAppli.CanvasMenu1.CanvasMenu['width']) * 0.995)) + "x" +
                      str(int(int(self.MainAppli.CanvasMenu1.CanvasMenu['height']) * 0.97)) + "+"
                      + str(int(self.MainAppli.SX * 0.007)) + "+" + str(int(self.MainAppli.SY * 0.09)))
        self.resizable(width=False, height=False)
        self.overrideredirect(True)

        self.Agenda = Agenda(self, locale='fr')
        self.Agenda.pack(fill="both", expand=True)
        self.Agenda.focus_set()

        self.Agenda.bind("<<CalendarSelected>>", self.on_click_day)
        self.FormatDate(self.Agenda.datetime.today())

    def on_click_day(self, _):
        self.Agenda.label.bind('<MouseWheel>', self.ActionMouseWheel)
        self.Agenda.label.bind('<Button-2>', self.AffichPlanningJour)
        self.FormatDate(self.Agenda.selection_get())
        self.MainAppli.IndexTP = 0
        self.MainAppli.AffichSelectTP()
        self.MainAppli.ModifTP(_)

    def ActionMouseWheel(self, _):
        self.MainAppli.ActionMouseWheelOnLabel(_)

    def AffichPlanningJour(self, _):
        self.MainAppli.AffichPlanningJour()

    def FormatDate(self, Date):
        self.DateSelected = DateFormat(Date.day, Date.month, Date.year).title()


class Agenda(Calendar):
    def __init__(self, master=None, **kw):
        Calendar.__init__(self, master, **kw)
        for i, row in enumerate(self._calendar):
            for j, self.label in enumerate(row):
                self._cal_frame.rowconfigure(i + 1, uniform=1)
                self._cal_frame.columnconfigure(j + 1, uniform=1)
                self.label.configure(justify="center", anchor="n", padding=(1, 4))

    def _display_days_with_othermonthdays(self):
        year, month = self._date.year, self._date.month

        cal = self._cal.monthdatescalendar(year, month)

        next_m = month + 1
        y = year
        if next_m == 13:
            next_m = 1
            y += 1
        if len(cal) < 6:
            if cal[-1][-1].month == month:
                i = 0
            else:
                i = 1
            cal.append(self._cal.monthdatescalendar(y, next_m)[i])
            if len(cal) < 6:
                cal.append(self._cal.monthdatescalendar(y, next_m)[i + 1])

        week_days = {i: 'normal' for i in range(7)}
        week_days[self['weekenddays'][0] - 1] = 'we'
        week_days[self['weekenddays'][1] - 1] = 'we'
        prev_m = (month - 2) % 12 + 1
        months = {month: '.%s.TLabel' % self._style_prefixe,
                  next_m: '_om.%s.TLabel' % self._style_prefixe,
                  prev_m: '_om.%s.TLabel' % self._style_prefixe}

        week_nb = cal[0][1].isocalendar()[1]
        modulo = max(week_nb, 52)
        for i_week in range(6):
            self._week_nbs[i_week].configure(text=str((week_nb + i_week - 1) % modulo + 1))
            for i_day in range(7):
                style = week_days[i_day] + months[cal[i_week][i_day].month]
                self.label = self._calendar[i_week][i_day]
                self.label.state(['!disabled'])
                txt = str(cal[i_week][i_day].day)
                self.label.configure(text=txt, style=style)
                if cal[i_week][i_day] in self._calevent_dates:
                    date = cal[i_week][i_day]
                    ev_ids = self._calevent_dates[date]
                    i = len(ev_ids) - 1
                    while i >= 0 and not self.calevents[ev_ids[i]]['tags']:
                        i -= 1
                    if i >= 0:
                        style = self.label.cget("style")
                        if style not in ['normal_om.%s.TLabel' % self._style_prefixe,
                                         'we_om.%s.TLabel' % self._style_prefixe]:
                            tag = self.calevents[ev_ids[i]]['tags'][-1]
                            self.label.configure(style='tag_%s.%s.TLabel' % (tag, self._style_prefixe))
                    text = '%s\n' % date.day + '\n'.join([self.calevents[ev]['text'] for ev in ev_ids])
                    self.label.configure(text=text)

    def _show_event(self, date):
        w, d = self._get_day_coords(date)
        if w is not None:
            self.label = self._calendar[w][d]
            if not self.label.cget('text'):
                return
            ev_ids = self._calevent_dates[date]
            i = len(ev_ids) - 1
            while i >= 0 and not self.calevents[ev_ids[i]]['tags']:
                i -= 1
            if i >= 0:
                style = self.label.cget("style")
                if style not in ['normal_om.%s.TLabel' % self._style_prefixe,
                                 'we_om.%s.TLabel' % self._style_prefixe]:
                    tag = self.calevents[ev_ids[i]]['tags'][-1]
                    self.label.configure(style='tag_%s.%s.TLabel' % (tag, self._style_prefixe))
            text = '%s\n' % date.day + '\n'.join([self.calevents[ev]['text'] for ev in ev_ids])
            self.label.configure(text=text)

    def _on_click(self, event):
        if self._properties['state'] == 'normal':
            self.label = event.widget
            if "disabled" not in self.label.state():
                day = self.label.cget("text")
                style = self.label.cget("style")
                if style in ['normal_om.%s.TLabel' % self._style_prefixe, 'we_om.%s.TLabel' % self._style_prefixe]:
                    if self.label in self._calendar[0]:
                        self._prev_month()
                    else:
                        self._next_month()
                if day:
                    if len(day) < 3:
                        day = int(day)
                    else:
                        day = int(day.split("\n")[0])
                    year, month = self._date.year, self._date.month
                    self._remove_selection()
                    self._sel_date = self.date(year, month, day)
                    self._display_selection()
                    if self._textvariable is not None:
                        self._textvariable.set(self.format_date(self._sel_date))
                    self.event_generate("<<CalendarSelected>>")

    def EffaceEvent(self, date):
        self.calevent_remove(date=date)
        self._reset_day(date)
        self.selection_set(date)


class PlanningJour:
    def __init__(self, container, ListTP, Font, MainAppli):
        self.MainAppli = MainAppli
        self.TPSelect = 0
        self.FrameTableur = tk.Frame(container)
        container.create_window(int(int(container['width']) * 0.5),
                                int(int(container['height']) * 0.513), anchor=tk.CENTER,
                                window=self.FrameTableur)
        self.scrollable_canvas = ScrollableCanvas(self.FrameTableur, int(int(container['width']) * 0.965),
                                                  int(int(container['height']) * 0.945))
        self.scrollable_canvas.grid(row=1, column=1)

        self.TabLabels = []
        self.TabLabelH = []
        c = 1
        for r in range(40):
            self.TabLabelCol = []
            if c == 1:
                text = str(int(c * (8 + r / 4))) + ' H'
            else:
                text = ''
            self.TabLabelH.append(tk.Label(self.scrollable_canvas.interior, text=text, relief=tk.FLAT,
                                           width=int(int(container['width']) * 0.003),
                                           height=int(int(container['height']) * 0.002),
                                           bg='#F0F0F0', font=Font, anchor=tk.N))
            self.TabLabelH[r].grid(row=r, column=0)
            c = c + 1
            if c == 5:
                c = 1
            for i in range(6):
                self.TabLabelCol.append(
                    tk.Label(self.scrollable_canvas.interior, text='', borderwidth=1, relief=tk.RIDGE,
                             width=int(int(container['width']) * 0.019),
                             height=int(int(container['height']) * 0.003), bg='white', font=Font))
                self.TabLabelCol[i].grid(row=r, column=i + 1)

            self.TabLabels.append(self.TabLabelCol)

        self.LabelTP = []
        self.MenuClicDroit = []
        self.NTP = 0
        for i in range(len(ListTP)):
            self.NTP += 1
            self.AffichTP(self.NTP, i + 1, ListTP[i][2], ListTP[i][3], self.MainAppli.MainAppli.BaseEnCours,
                          ListTP[i][4], ListTP[i][6], ListTP[i][5])

        for i in range(len(self.MenuClicDroit)):
            self.MenuClicDroit[i][0].add_command(label="Préparer le TP", command=self.PrepaTP)

        self.SelectTP(0)

    def AffichTP(self, NTP, Ncol, HDEB, HFIN, Type, Classe, Titre, NbrGr):
        hdeb = int(divmod(float(HDEB) * 60, 60)[0])
        mindeb = int(round(divmod(float(HDEB) * 60, 60)[1] / 5) * 5)
        hfin = int(divmod(float(HFIN) * 60, 60)[0])
        minfin = int(round(divmod(float(HFIN) * 60, 60)[1] / 5) * 5)

        LDeb = (hdeb - 8) * 4 + int(mindeb / 15)
        LFin = (hfin - 8) * 4 + int(minfin / 15)
        self.LabelTP.append([Ncol, LDeb, LFin, Titre])

        ListMenu = []
        for i in range(LDeb, LFin):
            self.TabLabels[i][Ncol].config(bg='#4169E1')
            ListMenu.append(tk.Menu(self.TabLabels[i][Ncol], tearoff=0))

            def GestEvt(evt):
                return self.ActionSelectTP(evt, NTP)

            def GestEvt2(evt):
                return self.AffichMenuClicDroit(evt, self.MenuClicDroit, NTP)

            self.TabLabels[i][Ncol].bind("<Button-3>", GestEvt2)
            self.TabLabels[i][Ncol].bind("<Button-1>", GestEvt)

        self.MenuClicDroit.append(ListMenu)

        Lactif = LDeb
        self.TabLabels[Lactif][Ncol].config(text='TP ' + Type + ' ' + Classe, fg='white')
        Lactif += 1
        if len(Titre) < 31:
            self.TabLabels[Lactif][Ncol].config(text=Titre, fg='white')
        else:
            ListTitre = Titre.split(' ')
            I = 0
            Ideb = 0
            Break = False
            text_titre = ListTitre[Ideb]
            while I < len(ListTitre) - 1:
                while len(text_titre) < 31:
                    if I + 1 <= len(ListTitre) - 1:
                        text_titre = text_titre + ' ' + ListTitre[I + 1]
                        I += 1
                    else:
                        Break = True
                        break
                if not Break:
                    text_titre = ListTitre[Ideb]
                    for i in range(Ideb + 1, I):
                        text_titre = text_titre + ' ' + ListTitre[i]
                    self.TabLabels[Lactif][Ncol].config(text=text_titre, fg='white')
                    Lactif += 1
                    Ideb = I
                    text_titre = ListTitre[Ideb]
                    if Lactif > LFin - 2:
                        Lactif = LFin - 2
                        Break = True
                        break
                else:
                    text_titre = ListTitre[Ideb]
                    for i in range(Ideb + 1, I + 1):
                        text_titre = text_titre + ' ' + ListTitre[i]
                    self.TabLabels[Lactif][Ncol].config(text=text_titre, fg='white')
                    break
            if not Break:
                self.TabLabels[Lactif][Ncol].config(text=ListTitre[I], fg='white')
        Lactif += 1

        if int(NbrGr) > 1:
            text = '(' + NbrGr + ' groupes)'
        else:
            text = '(' + NbrGr + ' groupe)'
        self.TabLabels[Lactif][Ncol].config(text=text, fg='white')

    def ActionSelectTP(self, _, n):
        self.SelectTP(n - 1)

    def SelectTP(self, n):
        for j in range(len(self.LabelTP)):
            for i in range(self.LabelTP[j][1], self.LabelTP[j][2]):
                self.TabLabels[i][self.LabelTP[j][0]].config(bg='#4169E1')

        for i in range(self.LabelTP[n][1], self.LabelTP[n][2]):
            self.TabLabels[i][self.LabelTP[n][0]].config(bg='blue')

        self.MainAppli.AffichProtocol(self.LabelTP[n][3])

    def AffichMenuClicDroit(self, event, MenuClicDroit, j):
        MenuClicDroit[j - 1][0].post(event.x_root, event.y_root)
        self.TPSelect = j - 1

    def PrepaTP(self):
        self.MainAppli.ActionCacheFrmPlanningTP()
        self.MainAppli.MainAppli.IndexElt = self.MainAppli.MainAppli.ListNomProd.index(self.LabelTP[self.TPSelect][3])
        self.MainAppli.MainAppli.FrmTP.SelectTP(self.MainAppli.MainAppli.IndexElt)


class NoPDF:
    def __init__(self, container, file, X, Y, RX, RY):
        self.ImgNoPdf = []
        img = Image.open(file)
        imgwsize = int((float(img.size[0]) * float(RX)))
        imghsize = int((float(img.size[1]) * float(RY)))
        img = img.resize((imgwsize, imghsize), Image.ANTIALIAS)
        self.ImgNoPdf.append(ImageTk.PhotoImage(img))

        self.CanvasImgNoPdf = CanvasApp(container, width=imgwsize, height=imghsize)
        container.create_window(X, Y, anchor=tk.CENTER, window=self.CanvasImgNoPdf)
        self.ImgCanvasImgNoPdf = self.CanvasImgNoPdf.create_image(0, 0, anchor=tk.NW, image=self.ImgNoPdf[0])


class Note:
    def __init__(self, container, path, W, H, X, Y, Text, MainAppli):
        self.MainAppli = MainAppli
        self.textNote = ''
        self.CanvasNote = CanvasMenu(container, path, W, H, X, Y, tk.CENTER)
        self.CanvasNote.CanvasMenu.bind("<Double-1>", self.CloseNote)
        self.ZoneText = tk.Text(self.CanvasNote.CanvasMenu, width=int(W * 0.1), height=int(H * 0.05), relief='flat',
                                bg='#F8F864')
        self.ZoneText.focus_set()
        self.CanvasNote.CanvasMenu.create_window(int(W * 0.5), int(H * 0.48), anchor=tk.CENTER, window=self.ZoneText)
        self.ZoneText.bind("<Double-1>", self.CloseNote)
        ChangeCursor(self.CanvasNote.CanvasMenu)
        ChangeCursor(self.ZoneText)
        self.ZoneText.insert(0.0, Text)

    def CloseNote(self, _):
        self.textNote = self.ZoneText.get(0.0, tk.END)[:-1]
        if self.textNote != '':
            self.MainAppli.SaveNote()
        else:
            self.MainAppli.SupNote()
        self.CanvasNote.CanvasMenu.destroy()
