from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.contrib.auth import login, authenticate, logout
from ServerApp.models import Query, Counter,Form, Request
from django.contrib.auth.models import User
from django.core.files.storage import default_storage
from django.core.files.storage import FileSystemStorage
import json,datetime,time
from threading import Thread
from django.core import serializers
from django.contrib.auth.decorators import user_passes_test
global G
G={}
global saved
saved=[]
global forms, responses,i,j
i=0
j=0
forms = ["""
<input type="text" id="hello">
"""]
responses =[]
newResponse=""
response = [""" <!DOCTYPE html>
<html lang="en">
<head>
    <style>
         .movable{
  position: absolute;
  z-index: 9;
  background-color: #f1f1f1;
  text-align: center;
  border: 1px solid #3f3e3e;
    };
   
    </style>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=1.0, initial-scale=1.0">	<head>
		<title>foobar</title>
		 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script>

	</head>
	<body background=""",""" style="background-repeat:no-repeat;background-position: 50% 1%;" onload="deleter();">
""","""</body>
<script type='text/javascript'>
      function deleter(){       
          var paras = document.getElementsByClassName('dropdown');
var i = 0;
for(i=0;i<paras.length;i++){
  paras[i].innerHTML="";
  }
paras = document.getElementsByClassName('delItems');
for(i=0;i<paras.length;i++){
  paras[i].innerHTML="";
  }
  }
</script>

	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
   <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
</html>
"""]
import random
# Create your views here.
crowd = [{"name":f"counter {i}", "crowd":random.randint(1,55)} for i in range(1,6)]

class Customer:
    def __init__(self,counter,token,time,t):
        self.token=token
        self.counter=counter
        self.queries=[]
        self.answers=[]
        self.forms=[]
        self.files=[]
        self.answerFiles=[]
        self.Name=""
        self.Dept=""
        self.CYear=''
        self.AYear=""
        self.answered=False
        if time!=0:
            self.time=t+time
        else:
            self.time=t

class Thread_P:
    def __init__(self,counter,thrd,time):
        self.counter = counter
        self.ListCustomers=[]
        self.Thrd=thrd
        self.index=0
        self.response_time=time
class Local_Server_Controller:
    def __init__(self):
        self.pindex=0
        self.requests=[]
        self.crowd={}
        self.date="datetime.date.today()"
        for Ctr in Counter.objects.all():
            self.crowd[Ctr.Counter] = 0
        #Customer("niranjantamhane","1"),Customer("RakeshAglave","2")
        self.nums={}
        self.threads={}
        for i in Counter.objects.all():
            #print(i.Counter.username)
            self.nums[i.Counter.username]=0
            self.threads[i.Counter.username]=Thread_P(i.Counter.username,Thread(target=self.Timer,args=[i.Counter.username]),i.Counter_Reply_Time)
            self.threads[i.Counter.username].Thrd.start()

    def Timer(self,Counter):
        while True:

            for i in self.threads[Counter].ListCustomers:
                if i.time>0:
                    i.time-=self.nums[Counter]
                    #print("<-----------------working--------------->",i.time,self.nums[Counter])
            time.sleep(1)

    def submit_form(self,request):
        if request.method=="POST":
            values = request.POST.items()
            formname = request.POST.get("formname")
            temp={}
            for i in values:
                temp[i[0]]=i[1]
            temp={formname:temp}
            responses.append(temp)
            return HttpResponse("Successfully Submitted Form")

    def testing(self,request):
        global newResponse
        return HttpResponse(newResponse)

    def upload_file(self,request):
        if request.method == 'POST':
            ##print(files.name)
            myfile = request.FILES['file']
            fs = FileSystemStorage(location="ServerApp/static/images") #defaults to   MEDIA_ROOT  
            filename = fs.save(myfile.name, myfile)
            file_url = fs.url(filename)
            #print(file_url)
            return HttpResponse(file_url)
            
    def Single_Counter(self,request):
        if request.method=="GET":
            x = request.GET.get("x")
            print(x)
            if x=="check":

                token = request.GET.get("token")
                try:
                    search = Request.objects.get(token=token)
                    
                    return JsonResponse({"Status":"Success","token":search.token,"subject":search.Subject,"status":search.Status,"DOA":search.DOA})
                except:
                    return JsonResponse({"Status":"Fail"})
            elif x=="yes":
                counter = request.GET.get("counter")
                ctr=counter
                counter = Counter.objects.get(Counter=counter)
                
                token = self.random_token()

                if self.threads[ctr].ListCustomers!=[]:
                    self.threads[ctr].ListCustomers.append(Customer(ctr,token,self.threads[ctr].ListCustomers[-1].time,self.threads[ctr].response_time))
                else:
                    self.threads[ctr].ListCustomers.append(Customer(ctr,token,0,self.threads[ctr].response_time))
                names = Form.objects.filter(Creator=counter)#Counter.objects.get(Counter="niranjantamhane")
                queries = Query.objects.filter(Counter=counter.Counter)
                crowd=len(self.threads[ctr].ListCustomers)-1
                return render(request, "counter.html", {"token":token,"queries":queries,"forms":names,"counter":counter,"crowd":crowd})
            elif x=="no":
                counter = request.GET.get("counter")
                token = request.GET.get("token")
                ctr=counter
                counter = Counter.objects.get(Counter=counter)
                names = Form.objects.filter(Creator=counter)#Counter.objects.get(Counter="niranjantamhane")
                queries = Query.objects.filter(Counter=counter.Counter)
                crowd=len(self.threads[ctr].ListCustomers)-1
                return render(request, "counter.html", {"token":token,"queries":queries,"forms":names,"counter":counter,"crowd":crowd})
            else:
                token = request.GET.get("token")
                counter=None
                for i in Counter.objects.all():
                    for tok in self.threads[i.Counter.username].ListCustomers:
                        if tok.token==token:
                            counter = tok.counter
                            break
                if counter==None:
                    return JsonResponse({"Status":"Fail"})
                ctr=counter
                counter = Counter.objects.get(Counter=counter)
                names = Form.objects.filter(Creator=counter)#Counter.objects.get(Counter="niranjantamhane")
                queries = Query.objects.filter(Counter=counter.Counter)
                crowd=len(self.threads[ctr].ListCustomers)-1
                return JsonResponse({"Status":"Success","token":token,"counter":ctr})
                               
        
    def form_return(self,request): ## dynamically by https://stackoverflow.com/questions/64624050/how-to-create-a-dynamic-link-in-django
        if request.method=="GET":
            formid = int(request.GET.get("id"))
            form = Form.objects.get(id=formid)
            
            return render(request,"form_.html",{"form":form})

    def form_creator(self,request):
        if request.user.is_authenticated:
            ctr =Counter.objects.get(Counter=request.user.username)
            x = Form.objects.filter(Creator=ctr)
            theme = ctr.Counter_Theme
            return render(request, "form_creator.html",{"files":x,"theme":theme})
        else:
            return self.Counters_View(request)

    def counter_Login(self,request):
        if request.user.is_authenticated:
            return self.user_dashboard(request)
        else:
            if request.method == "POST":
                username = request.POST.get('username')
                password = request.POST.get('password')
                user = authenticate(username=username, password=password)
                if user:
                    if user.is_active:
                        login(request, user)
                        return JsonResponse({"Status":"Success"})
                    else:
                        return JsonResponse({"Status":"Failure"})
                else:
                    return JsonResponse({"Status":"Failure"})
            else:
                #print("this is expiry age",request.session.get_expiry_age())
                return render(request,"login.html")

    def get_numFront(self,token):
        count=0
        for i in G:
            if i==token:
                break
            count+=1
        return count 

    def user_dashboard(self,request):
        if request.user.is_authenticated:
            if request.method=="POST":
                status = request.POST.get("Status")
                want = request.POST.get("want")
                myfiles =[]
                for file in range(5):
                    try:
                        myfile =request.FILES["file"+str(file)]
                        fs = FileSystemStorage(location="ServerApp/static/images") #defaults to   MEDIA_ROOT  
                        filename = fs.save(myfile.name, myfile)
                        file_url = fs.url(filename)
                        myfiles.append(file_url)
                        print("Fileeeeee--------->",myfiles[-1])
                    except:
                        print("Not file")
                    print(file)
            
                if want == "answers": ########### Convert to post
                    token=request.POST.get("Status")
                    answers = json.loads(request.POST.get("data"))
                    for i in self.threads[request.user.username].ListCustomers:
                        if i.token==token:
                            i.answers=answers
                            i.answered=True
                            i.answerFiles=myfiles
                    print(token,answers)
                    return JsonResponse({"Status":"Success"})
            if request.method=="GET":
                status = request.GET.get("Status")
                want = request.GET.get("want")
                #print("Dashboard---->",status,want)
                if want=="settingsChange":
                    s=request.GET.get("data")
                    s = s[2:-2]
                    if ',' in s:
                        s = s.split('","')
                    else:
                        s = [s]
                    obj = Counter.objects.get(Counter=request.user.username)
                   # [Counter_Title,Counter_Duty,theme,Counter_Reply_Time]
                    print(s)
                    obj.Counter_Title = s[0]
                    obj.Counter_Duty = s[1]
                    obj.Counter_Theme = s[2]
                    obj.Counter_Reply_Time =int(s[3])
                    obj.save()
                    return JsonResponse({"Status":"Success"})
                elif want =="All_Customers":
                    all=[]
                    for i in self.threads[request.user.username].ListCustomers:
                        all.append({"token":i.token,"Name":i.Name,"Status":i.answered})
                    return JsonResponse({"StatuS":"Success","all":all})
                elif want == "ans":
                    if status!=None:
                        #print("level 0---->")
                        if status=="on":
                            self.nums[request.user.username]=1
                            
                        elif status=="off":
                            self.nums[request.user.username]=0
                    
                    return JsonResponse({"Works":"Man"})
                elif want=="crowd":
                    return JsonResponse({"crowd":len(self.threads[request.user.username].ListCustomers),"Status":"Success"})

                elif want == "queries":
                    index = request.GET.get("index")
                    x= request.GET.get("Status")
                    ##print("here is the spot",index)
                    try:
                        if x=="prev":
                            if self.threads[request.user.username].index>-1:
                                self.threads[request.user.username].index-=1
                                temp=self.threads[request.user.username].ListCustomers[self.threads[request.user.username].index]
                                
                        elif x=="next":
                            if self.threads[request.user.username].index<len(self.threads[request.user.username].ListCustomers):
                                self.threads[request.user.username].index+=1
                                temp=self.threads[request.user.username].ListCustomers[self.threads[request.user.username].index]
                        elif x=="Current":
                            token = request.GET.get("data")[1:-1]
                            for i in self.threads[request.user.username].ListCustomers:
                                print(token,i.token)
                                if token==i.token:
                                    print("Comes here lets see",token,i.token)
                                    temp=i
                                    break
                        
                        token=temp.token
                        response={token:temp.queries,"files":temp.files,"Status":"Success","answered":temp.answered,"Name":temp.Name,"Dept":temp.Dept,"CYear":temp.CYear,"AYear":temp.AYear}
                        return JsonResponse(response)
                    except Exception as e:
                        print("Here is exception: ",e)
                        return JsonResponse({"Success":"Fail"})
                elif want == "answers": ########### Convert to post
                    token=request.GET.get("Status")
                    answers = json.loads(request.GET.get("data"))
                    for i in self.threads[request.user.username].ListCustomers:
                        if i.token==token:
                            i.answers=answers
                            i.answered=True
                    print(token,answers)
                    return JsonResponse({"Status":"Success"})
                elif want=="mySettings":
                    cntr = Counter.objects.get(Counter=request.user.username)

                    return JsonResponse({"Status":"Success","Counter_Title":cntr.Counter_Title,"Counter_Duty":cntr.Counter_Duty,"Counter_Theme":cntr.Counter_Theme,"Counter_Reply_Time":cntr.Counter_Reply_Time})
                elif want=="myForms":
                   
                    return self.form_creator(request)
                elif want =="query":
                    id = status
                    query = Query.objects.get(id=id)
                    return JsonResponse({'query':query.query,'DOC':query.DOC,"id":query.id})
                elif want=="querySave":
                    id = int(status)
                    querynew=request.GET.get("data")[1:-1]
                    if id!=-1:
                        query = Query.objects.get(id=id)
                        query.query=querynew
                    else:
                        query = Query.objects.create(query=querynew,DOC=datetime.datetime.now(),Counter=request.user)
                    
                    query.save()
                    return JsonResponse({"Status":"Success"})
                elif want=='queryDelete':
                    id = status
                    query = Query.objects.get(id=id)
                    query.delete()
                    return JsonResponse({"Status":"Success"})
                elif want=="myQueries":
                    
                    queries = Query.objects.filter(Counter=request.user)
                    data = []
                    for query in queries:
                        data.append({'query':query.query,'DOC':query.DOC,"id":query.id})
                    return JsonResponse({"Status":"Success","Data":data})
                elif want=="logout":
                    logout(request)
                    return JsonResponse({"Status":"Success","Data":"Signout"})
                elif want=="PrincipalRequests":
                    searches=[]
                    search = request.GET.get("token")
                    for i in Request.objects.all():
                        searches.append({"token":i.token,"Name":i.Student_Name,"Status":i.Status,"Subject":i.Subject})
                    return JsonResponse({"Status":"Success","searches":searches})
                elif want=="Request":
                    print("Comes here")
                    search = request.GET.get("Status")
                    data = Request.objects.get(token=search)
                    s = data.files[2:-2]
                    if ',' in s:
                        s = s.split("', '")
                    else:
                        s = [s]
                    return JsonResponse({"StatuS":"Success","Student_Name":data.Student_Name,"Dept":data.Dept,"Current_Year":data.Current_Year,"Admission_Year":data.Admission_Year,"Subject":data.Subject,"Request":data.Request,"files":s,"DOA":data.DOA,"Status":data.Status,"token":data.token})
            obj = Counter.objects.get(Counter=request.user.username)
            return render(request, "dashboard.html",{"Counter":obj})
        else:
            return self.counter_Login(request)
    def random_token(self):
        import random
        global G
        num=""
        for i in range(10):
            num+=str(random.randint(0,10))
        if num in G:
            return self.random_token()
        else:
            return num

    def get_test(self,request):
        if request.method == "POST":
            token = str(request.POST.get("token"))
            ##print(token)
            decision = request.POST.get("decision")
            counter = request.POST.get("counter")
            myfiles =[]
            for file in range(5):
                try:
                    myfile =request.FILES["file"+str(file)]
                    fs = FileSystemStorage(location="ServerApp/static/images") #defaults to   MEDIA_ROOT  
                    filename = fs.save(myfile.name, myfile)
                    file_url = fs.url(filename)
                    myfiles.append(file_url)
                    print("Fileeeeee--------->",myfiles[-1])
                except:
                    print("Not file")
                print(file)
            
            if decision=="Submit":
                ids = json.loads(request.POST.get("queries"))
                #print(ids)
                bigQuery = request.POST.get("bigQuery")
                print("Hereeee-------------->0")
                queries = [[Query.objects.get(id=int(v[0])).query,v[1]] for v in ids]
                print("Hereeee-------------->1")
                if bigQuery!="":
                    queries.append([bigQuery,""])
                    print("Hereeee-------------->2")
                print("Hereeee-------------->3")
                for cust in self.threads[counter].ListCustomers:
                    #print(cust.token,token)
                    if cust.token==token:
                        cust.queries=queries
                        cust.files=myfiles
                        cust.Name = request.POST.get("Name")
                        cust.Dept = request.POST.get("Dept")
                        cust.CYear = request.POST.get("CYear")
                        cust.AYear = request.POST.get("AYear")
                        #print("IT worksss",cust.queries)
                print("Hereeee-------------->4")
                return JsonResponse({"Status":"Success"})

            return JsonResponse({"Status":"Fail"})
        elif request.method == "GET":
            token = str(request.GET.get("token"))
            ##print(token)
            decision = request.GET.get("decision")
            counter = request.GET.get("counter")
            ###print([k.token for k in self.threads[counter].ListCustomers])
            if decision =="timer":
                if token=="X":
                    ##print("Working...")
                    rt=str(self.random_token())
                    ##print("RT",rt)
                    if self.threads[counter].ListCustomers!=[]:
                        self.threads[counter].ListCustomers.append(Customer(counter,rt,self.threads[counter].ListCustomers[-1].time,self.threads[counter].response_time))
                    else:
                        self.threads[counter].ListCustomers.append(Customer(counter,rt,0,self.threads[counter].response_time))
                    return JsonResponse({"Status":"Success","value":rt})
  
                elif token not in [k.token for k in self.threads[counter].ListCustomers]:
                    ##print("This XX")
                    rt=str(self.random_token())
                    ##print("Counter her it is",counter,rt)
                    if self.threads[counter].ListCustomers!=[]:
                        self.threads[counter].ListCustomers.append(Customer(counter,rt,self.threads[counter].ListCustomers[-1].time,self.threads[counter].response_time))
                    else:
                        self.threads[counter].ListCustomers.append(Customer(counter,rt,0,self.threads[counter].response_time))
                    return JsonResponse({"Status":"Success","value":"X"+rt})
 
                else:
                    #print("This work")
                    #G[token].time-=1
                    for i in self.threads[counter].ListCustomers:
                        if i.token==token:
                            num=i.time
                    #print(num)
                    n=str(self.get_numFront(token))
                    #rr=str(num)+"|"+n
                    return JsonResponse({"Status":"Success","n":n,"num":num,"value":" "})
                    #return render(request, "return.html", {"text":rr})
            elif decision=="check":
                if token in [k.token for k in self.threads[counter].ListCustomers]:
                    newToken = str(request.GET.get("queries")[1:-1])
                    print(token,newToken)
                    
                    if token!=newToken:
                        dex=0
                        for i in self.threads[counter].ListCustomers:
                            if i.token == newToken:
                                self.threads[counter].ListCustomers.pop(dex)
                                break
                            dex+=1
                        
                    return JsonResponse({"Status":"Success","tokenStatus":True,"value":"0"})
                else:
                    return JsonResponse({"Status":"Success","tokenStatus":False,"value":"0"})
            elif decision=="Answers":
                answers=[]
                answerFiles=[]
                for i in self.threads[counter].ListCustomers:
                        if i.token==token:
                            answers=i.answers
                            answerFiles=i.answerFiles
                            answered = i.answered
                return JsonResponse({"Status":"Wait","value":" ","Answers":answers,"answerFiles":answerFiles,"answered":answered})
            
    def check_token(self,request):
        if request.method == "GET":
            token = request.GET.get("token")
            if token in G:
                num="True"
            else:
                num="False"
            return render(request, "return.html", {"text":num})

    def add_query(self,request):
        if request.user.is_authenticated:
            if request.method == "POST":
                import datetime
                query = request.POST.get("query")
                #print(query)
                DOC = datetime.datetime.now()
                try:
                    Counter = User.objects.get(username=request.user)
                except:
                    print("Not user l;ike that")
                obj = Query.objects.create(query=query,DOC=DOC,Counter=Counter)
                obj.save()
                return self.test_func(request)
            else:
                return render(request, "add_query.html")
        else:
            return HttpResponse("Not authenticated")


    def Counters_View(self,request):
        counters=[]
        for i in Counter.objects.all():
            counters.append({"counter":i,"crowd":self.crowd[i.Counter]})
        return render(request,"counters.html",{"counters":counters})

    def SPV_Method(self,request):
        global newResponse, saved
        if request.method=="GET":
            action = request.GET.get("action")
            responseGet = request.GET.get("response")
            background = request.GET.get("bg")
            name = request.GET.get("filename")
            rename =request.GET.get("rename")
            count = int(request.GET.get("count"))
            openf = request.GET.get("open")
            idx = int(request.GET.get("id"))
            
            if action == "delete":
                obj = Form.objects.get(id=idx)
                obj.delete()
                return JsonResponse({"Status":"Success"})
            #print(action, background)
            elif action=="save":
                #print("got it")
                j=0
                if idx != -1:
                    #print(idx)
                    idx = Form.objects.get(id=idx)
                    idx.Name=name
                    idx.LastEdit = datetime.datetime.now()
                    idx.inputs = count
                    idx.htmlForm = responseGet
                    idx.save()
                    return JsonResponse({"Status":"Present","ID":idx.id})
                elif idx==-1:
                    newSave = Form.objects.create(DOC=datetime.datetime.now(),
                    Creator=Counter.objects.get(Counter=request.user.username),Name=name,
                    htmlForm=responseGet,LastEdit=datetime.datetime.now(),
                    inputs=count,Background=background)
                    
                    newSave.save()
                    #saved.append([name,background,responseGet,count])
                    return JsonResponse({"Status":"Saved","id":newSave.id})
                 
            elif action=="open":
                present = True
                #print("Open File___>---------------",openf)
                try:
                    obj = Form.objects.get(id=openf)
                except:
                    present=False
                if present:
                    #print("Here is the fault_______________________-----------------------")
                    try:
                        bg=obj.Background.url
                    except:
                        bg=""
                    newResponse = {"Status":"Success","filename":obj.Name,"background":bg, "context":obj.htmlForm,"inputs":obj.inputs,"id":obj.id}
                    return JsonResponse(newResponse)
                else:
                    return JsonResponse({"Status":"Fail"})
            elif action=="preview":
                #print(background, responseGet)
                newResponse = response[0]+background+response[1]+responseGet+response[2]
                #print(newResponse)
            elif action=="rename":
                #print(name,rename)
                ##print(saved)
                present=False
                try:
                    obj = Form.objects.get(id=idx)
                except:
                    present=False
                if present:
                    obj.Name=rename
                    obj.save()
                    newResponse = "Present"
                else:
                    newResponse = "NPresent"
            return HttpResponse(newResponse)

    def save_form_response(self,request):
        if request.method=='POST':
            #print(request.POST)
            temp={}
            import json
            temp={"qw":"b","input1":"hello"}
            return render(request,"form.html",temp)
        return render(request,"form.html",{"response":"{ }"})

    def Form_Checking(self,request):
        counter = Counter.objects.get(Counter=request.user.username)
        forms = Form.objects.filter(Creator=counter)
        return render(request,"form_checking.html",{"forms":forms})

    def Form_Changer(self,request):
        global j
        if request.method=="GET":
            change = request.GET.get("change")
            formid = int(request.GET.get("formname"))
            if change=="load":
                i = Form.objects.get(id=formid)
                return HttpResponse(i.htmlForm)
            elif change=="next":
                num = int(request.GET.get("resnum"))
                temp = [i for i in responses if formid in i]
                ans = (num+1)%len(temp)
                return JsonResponse(temp[ans], safe=False)

            return HttpResponse("working")

    def Home(self,request):
        return render(request,"home.html")

    def Principal_Request(self,request):
        if request.method=="GET":
            token = self.random_token()
            return render(request,"PrincipalRequest.html",{"token":token})
        elif request.method=="POST":
            myfiles =[]
            for file in range(5):
                try:
                    myfile =request.FILES["file"+str(file)]
                    print(myfile)
                    fs = FileSystemStorage(location="ServerApp/static/images") #defaults to   MEDIA_ROOT  
                    filename = fs.save(myfile.name, myfile)
                    file_url = fs.url(filename)
                    myfiles.append(file_url)
                    print("Fileeeeee--------->",myfiles[-1])
                except:
                    print("Not file")
                print(file)
            Student_Name=request.POST.get("Name")
            Dept = request.POST.get("Dept")
            Token = request.POST.get("token")
            Current_Year = request.POST.get("CYear")
            Admission_Year = request.POST.get("AYear")
            Subject = request.POST.get("Subject")
            Requesto = request.POST.get("Request")
            files = str(myfiles)
            DOA= datetime.datetime.now()
            Status = "Pending"
            obj = Request.objects.create(Student_Name=Student_Name,
            Dept=Dept, token=Token,Current_Year=Current_Year,
            Admission_Year=Admission_Year,Subject=Subject,Request=Requesto,
            files=files, DOA = DOA, Status=Status)
            obj.save()
            return JsonResponse({"Status":"Success"})

    def is_principal(self, user):
        return user.groups.filter(name="Principals").exists()

    def Principal_View(self,request):
        if request.user.is_authenticated:
            if self.is_principal(request.user):
                if request.method=="GET":
                    date = request.GET.get("date")
                    move = request.GET.get("move")
                    
                    print(date,move)
                    if move=="prev" or move=="next":
                        x = date.split("-")
                        date=datetime.date(int(x[0]),int(x[1]),int(x[2]))
                        self.requests=[]
                        x=Request.objects.all()
                        for i in x:
                            if i.DOA.date()==self.date:#troubled a lot 5-19-2021 6:57pm
                                self.requests.append(i)
                        if self.date!=date:
                            self.pindex=0
                            self.date=date
                        
                    
                        elif self.date==date and self.requests!=[]:
                            if move=="next":
                                self.pindex = (self.pindex+1)%len(self.requests)
                            elif move=="prev":
                                self.pindex =(self.pindex-1)%len(self.requests)
                            
                        if len(self.requests)>0 and self.pindex < len(self.requests) and self.pindex>=0:
                            data = self.requests[self.pindex]
                        else:
                            data = None
                            return JsonResponse({"Status":"Fail"})
                        print(data.files)
                        s = data.files[2:-2]
                        if ',' in s:
                            s = s.split("', '")
                        else:
                            s = [s]
                        print(s[0])
                        return JsonResponse({"StatuS":"Success","Student_Name":data.Student_Name,"Dept":data.Dept,"Current_Year":data.Current_Year,"Admission_Year":data.Admission_Year,"Subject":data.Subject,"Request":data.Request,"files":s,"DOA":data.DOA,"Status":data.Status,"token":data.token})
                    elif move=="Done":
                        token = request.GET.get("token")
                        Status = request.GET.get("date")
                        obj = Request.objects.get(token=token)
                        obj.Status = Status
                        obj.save()
                        print(token, Status)
                        return JsonResponse({"StatuS":"Success"})
                    elif move=="Search":
                        searches=[]
                        search = request.GET.get("token")
                        for i in Request.objects.all():
                            if search in i.token or search.lower() in i.Student_Name.lower():
                                searches.append({"token":i.token,"Name":i.Student_Name,"Status":i.Status,"Subject":i.Subject})
                        return JsonResponse({"StatuS":"Success","searches":searches})
                    elif move=="GetAll":
                        searches=[]
                        search = request.GET.get("token")
                        for i in Request.objects.all():
                            searches.append({"token":i.token,"Name":i.Student_Name,"Status":i.Status,"Subject":i.Subject})
                        return JsonResponse({"StatuS":"Success","searches":searches})
                    elif move=="display":
                        search = request.GET.get("token")
                        data = Request.objects.get(token=search)
                        s = data.files[2:-2]
                        if ',' in s:
                            s = s.split("', '")
                        else:
                            s = [s]
                        return JsonResponse({"StatuS":"Success","Student_Name":data.Student_Name,"Dept":data.Dept,"Current_Year":data.Current_Year,"Admission_Year":data.Admission_Year,"Subject":data.Subject,"Request":data.Request,"files":s,"DOA":data.DOA,"Status":data.Status,"token":data.token})
                return render(request,"principalView.html")
            else:
                return HttpResponse("Not Principal")
        else:
            if request.method == "POST":
                username = request.POST.get('username')
                password = request.POST.get('password')
                user = authenticate(username=username, password=password)
                if user:
                    if user.is_active:
                        if self.is_principal(user):
                            login(request, user)
                        else:
                            return JsonResponse({"Status":"Failure"})
                        return JsonResponse({"Status":"Success"})
                    else:
                        return JsonResponse({"Status":"Failure"})
                else:
                    return JsonResponse({"Status":"Failure"})
            else:
                #print("this is expiry age",request.session.get_expiry_age())
                return render(request,"login.html")



RequestProcessor = Local_Server_Controller()
