from django.shortcuts import redirect, render
from django.contrib.auth.views import LoginView
from django.contrib.auth import authenticate, login
from django.contrib import messages
from BasicData.model_link import *
from django.contrib.auth.models import Group

from .custom_admin_form import CsvUploadForm
from .custom_fonctions import get_etudian_moyenne
import datetime
from session_tracking.utils import *


from BasicData.models import Enseignant,Etudiant, Annee,ParcoursSemestre
from Scolarite.models import AgentScolarite


# Create your views here.
FIC = "/home/mosco/Téléchargements/mailUE.csv"



class UserLoginView(LoginView):
    template_name = "EspaceEnseignant/login.html"
    next_page = "EspaceEnseignant:Home"
    redirect_authenticated_user = True
    redirect_field_name = next_page

    # def get_

def loginView(request):

    # GESTION DE LA VALIDITE DES EMPLOIS DU TEMPS
    validites = Validite.objects.filter(done=False)
    infos = FlashInfo.objects.filter(published=True)
    diffs = Sondage.objects.filter(published=True)
    dtnow = datetime.datetime.today().date()

    # VALIDITE EMPLOIS DU TEMPS
    for validite in validites:
        if validite and dtnow > validite.dateFin:
            validite.done=True
            validite.save()
        else:
            pass

    # FLASH INFOS
    for info in infos:
        if info and info.limite and dtnow > info.limite:
            info.published=False
            info.save()
        else:
            pass

    # SONDAGE
    for dif in diffs:
        if dif and dif.limite and dtnow > dif.limite:
            dif.publier=False
            dif.save()
        else:
            pass

    if request.method == "POST":
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(request, username=username, password=password)
        if user is not None:
            login(request, user)
            #track_login(user.email)
            # Redirect to a success page.

            if Etudiant.objects.filter(email=user.email,actif =True).last():
                return redirect("EspaceEtudiant:liste_etudiant_ue")
            # simple Enseignant
            elif Enseignant.objects.filter(email=user.email,is_staff=False,profile=True,is_ufr_dg=False,is_respo=False,is_pr=False,is_vp=False).last():
                return redirect("EspaceEnseignant:enseignant_profile")
            # DR UFR
            elif Enseignant.objects.filter(email=user.email, is_staff=False, is_ufr_dg=True,is_pr=False,is_vp=False,is_respo=False).last():
                return redirect("EspaceEnseignant:ufr_home")
            # RESPONSABLE PEDAGOGIQUE
            elif Enseignant.objects.filter(email=user.email, is_staff=False,is_ufr_dg=False, is_respo=True,is_pr=False,is_vp=False).last():
                return redirect("EspaceEnseignant:respo_pedag_home")
            # PRESIDENT DE L'USP
            elif Enseignant.objects.filter(email=user.email, is_staff=False, is_ufr_dg=False, is_respo=False,is_pr=True, is_vp=False).last():
                return redirect("EspaceEnseignant:president_usp")
            # VICE PRESIDENT DE L'USP
            elif Enseignant.objects.filter(email=user.email, is_staff=False, is_ufr_dg=False,is_respo=False, is_pr=False, is_vp=True).last():
                return redirect("EspaceEnseignant:vice_president_usp")
            # AGENT DE LA SCOLARITE
            elif AgentScolarite.objects.filter(email=user.email).last():
                return redirect("Scolarite:ags_home")
            # DRH - DIRECTEUR
            elif Personnel.objects.filter(email=user.email,resposabilite__libelle='Responsable DRH').last():
                return redirect("EspaceDRH:drh_home")
            # SIMPLE PERSONNEL
            elif Personnel.objects.filter(email=user.email,resposabilite__libelle='Aucun').last():
                return redirect("EspacePAT:pat_home")
            # CUSTOM ADMIN
            elif User.objects.filter(email=user.email, is_superuser=True).last():
                return redirect("BasicData:usp_admin")
            else:
                messages.error(request, 'Accès interdit')
                return redirect("BasicData:login")

        else:
            messages.error(request, "Veillez verifier que vous entrez les bonnes informations de connexion !")
            return redirect("BasicData:login")
    else:
        return render(request, "BasicData/login.html")



ANNEE = "/home/jdmi5414/pedagogie.univ-sp.net/usp_pedagogie/BasicData/csv/annee.csv"
DOAMINE = "/home/jdmi5414/pedagogie.univ-sp.net/usp_pedagogie/BasicData/csv/domaine.csv"
MENTION = "/home/jdmi5414/pedagogie.univ-sp.net/usp_pedagogie/BasicData/csv/mention.csv"
PARCOURS = "/home/jdmi5414/pedagogie.univ-sp.net/usp_pedagogie/BasicData/csv/parcours.csv"
SESSION = "/home/jdmi5414/pedagogie.univ-sp.net/usp_pedagogie/BasicData/csv/session.csv"
UFR = "/home/jdmi5414/pedagogie.univ-sp.net/usp_pedagogie/BasicData/csv/ufr.csv"
SEMESTRE = "/home/jdmi5414/pedagogie.univ-sp.net/usp_pedagogie/BasicData/csv/semestre.csv"
UE = "/home/jdmi5414/pedagogie.univ-sp.net/usp_pedagogie/BasicData/csv/ue.csv"
ECUE = "/home/jdmi5414/pedagogie.univ-sp.net/usp_pedagogie/BasicData/csv/ecue.csv"
ARHAI = "/home/jdmi5414/pedagogie.univ-sp.net/usp_pedagogie/BasicData/csv/mailARHAI.csv"
MPSI = "/home/jdmi5414/pedagogie.univ-sp.net/usp_pedagogie/BasicData/csv/mailMPSI.csv"
SDM = "/home/jdmi5414/pedagogie.univ-sp.net/usp_pedagogie/BasicData/csv/mailSDM.csv"
TES = "/home/jdmi5414/pedagogie.univ-sp.net/usp_pedagogie/BasicData/csv/mailTES.csv"
ENSEIGNANT = "/home/jdmi5414/pedagogie.univ-sp.net/usp_pedagogie/BasicData/csv/mailUE.csv"

Fichiers =[ARHAI,MPSI,SDM,TES]

Fichier_Genre ="/Users/moryouattara/Desktop/Pycharm-projects/usp_pedagogie_v1.0.6/BasicData/fichiers/ARHAI.csv"
Fichier_Genre_TES ="/Users/moryouattara/Desktop/Pycharm-projects/usp_pedagogie_v1.0.6/BasicData/fichiers/TES.csv"
Fichier_Genre_SDM ="/Users/moryouattara/Desktop/Pycharm-projects/usp_pedagogie_v1.0.7/BasicData/fichiers/SDM_Genre.csv"
Fichier_Genre_MPSI ="/Users/moryouattara/Desktop/Pycharm-projects/usp_pedagogie_v1.0.7/BasicData/fichiers/MPSI_2022_Genre.csv"

FueMPSI = '/Users/moryouattara/Desktop/Pycharm-projects/usp_pedagogie_v1.0.6/BasicData/fichiers/UeMPSI-2022-05-21.csv'
FEtudiantMPSI = '/Users/moryouattara/Desktop/Pycharm-projects/usp_pedagogie_v1.0.6/BasicData/fichiers/mailMPSI.csv'


NID_MPSI = '/Users/moryouattara/Desktop/Pycharm-projects/usp_pedagogie_v1.0.7/BasicData/fichiers/NCE_VS_IDPermanent.csv'
NID_ARHAI = '/Users/moryouattara/Desktop/Pycharm-projects/usp_pedagogie_v1.0.7/BasicData/fichiers/NID_ARHAI.csv'
NID_SDM = '/Users/moryouattara/Desktop/Pycharm-projects/usp_pedagogie_v1.0.7/BasicData/fichiers/NID_SDM.csv'
NID_TES = '/Users/moryouattara/Desktop/Pycharm-projects/usp_pedagogie_v1.0.7/BasicData/fichiers/NID_TES.csv'

ETD_LOGIN = "/Users/moryouattara/Desktop/Pycharm-projects/usp_pedagogie_v1.0.7/BasicData/fichiers/EMAIL_INSTITUTIONNEL_FINAL.csv"

#ivstp = "/Users/moryouattara/Desktop/Pycharm-projects/usp_pedagogie_v1.0.7/BasicData/fichiers/LISTE_IVESTP.csv"

def remplissage(request):
    #add_genre(Fichier_Genre_SDM)
    #add_genre_new(Fichier_Genre_MPSI)
    #enseignantUfr_update()
    #ues = ue_update(4,FEtudiantMPSI) # Add student Gender
    #ue_update_semestre()
    #etudiant_ufr_update()

    #+++++++++++++++++
    ues = Ue.objects.all()
    ecues = Ecue.objects.all()
    #ue_ecue_filed_update(ues)
    #ue_ecue_filed_update(ecues)
    #++++++++++++++++++++++++
    #set_evaluation_default_session()
    #update_etudiant_process([1,3,3,4,4])

    #nce_update(NID_TES)
    #reset_edt_field_mode()
    #update_etudiant_email(ETD_LOGIN)
    #email_for_cpanel_import(ivstp)
    #update_enseignant_password()
    #update_edt_type()
    #update_edt()
    #update_ue('PHYLOSOPHIE','PHILOSOPHIE')
    #update_ue('EXPRSSION. ECRITE','EXPRESSION. ECRITE')

    #update_ecue('PHYLOSOPHIE','PHILOSOPHIE')
    #update_ecue('EXPRSSION. ECRITE','EXPRESSION. ECRITE')

    return render(request, 'BasicData/remplir.html')


def test_view(request):
    form = CsvUploadForm()
    if request.method == 'POST':
        form = CsvUploadForm(request.POST or None, request.FILES or None)
        etobj = None
        if form.is_valid():
            form.save()
            cd = form.cleaned_data
            form = CsvUploadForm()
            obj = Csv.objects.get(activated=False)
            obj.activated = True
            obj.save()

            # ON OUVRE LE FICHIER
            #datas = pd.read_csv(fichier, delimiter=';')
            fichier = obj.file_name.path
            datas = pd.read_csv(fichier, delimiter=';')
            datas.dropna(how="all", inplace=True)
            mail = []
            pwd = []
            nm = []
            pr = []
            qt = []
            for i, data in datas.iterrows():
                nom = str(data['NOM']).lower().replace("'","")
                prenoms = str(data['PRENOMS']).lower().split(' ')[0].replace("'","")
                poste = str(data['PERSONNEL'])
                #print(poste)
                ps=''
                if poste == 'ADMINISTRATIF':
                    ps = 'adm'
                elif poste == 'ENSEIGNANT':
                    ps = 'ens'
                elif poste == 'ENCADREMENT':
                    ps = 'enc'
                elif poste == 'TECHNIQUE':
                    ps = 'tec'
                elif poste == 'CABINET COMPTABLE':
                    ps = 'cc'
                elif poste == 'CABINET RH ET JURIDIQUE':
                    ps = 'rh'
                elif poste == 'STAGIAIRE':
                    ps = 'sta'

                if '.' in prenoms:
                    prenoms = str(data['PRENOMS']).lower().split(' ')[1].replace("'", "")
                #fn = nom+'.'+prenoms+'@ivestp.net'
                fn = nom+'.'+prenoms+'.'+ps+'@ivestp.net'
                #fn = nom+'.'+prenoms+'.'+ps
                mail.append(fn.replace(" ",""))
                pwd.append(generer_password(10))
                nm.append(data['NOM'])
                pr.append(data['PRENOMS'])
                qt.append(10)

            zip_data = zip(nm, pr, mail, pwd, qt)
            response = HttpResponse(content_type='text/csv')
            response['Content-Disposition'] = 'attachment; filename=EMAIL_INSTITUTIONNEL.csv'
            writer = csv.writer(response, delimiter=';')
            writer.writerow(['Nom', 'Prenoms', 'Email', 'Password', 'Quota'])
            studs = zip_data
            for std in studs:
                writer.writerow(std)
            return response

    context={
        'form':form
    }
    return render(request,'BasicData/utils.html',context)

