import requests
import threading
import time as t
from queue import Queue
import json
import util
class Requester():

    def __init__(self,filename,threads=10):
        self.loadDataFromFile(filename)      
        self.taskNumber=0
        self.startingTime=t.time()
        self.setupWorkers(threads)
        
    def loadDataFromFile(self,filename):
       # with open(filename) as f:
        #self.data=json.load(filename)
            #print(self.data)    
        self.data=filename
    def setupAddingThread(self):
        thread = threading.Thread(target = self.addTasks)
        thread.daemon = True
        thread.start()

    def addTasks(self):
        
        for key,value in self.data.items():
            if key!=key: #NaN
                continue
            try:
                while float(key)>=t.time()-self.startingTime:
                    pass
                req=0 
                for i in range(value["numberOfTasks"]):
                    self.queue.put(value)
                    req+=1
                if req>0:
                    util.log("Added {} to queue".format(req))
            except Exception as e:
                print(e)
        self.queue.join()
        util.log("Finished!")
        #util.log("Requests: ",self.taskNumber,"time: ",t.time()-self.startingTime)
        

    def connect(self):
        while True:
            try:
                taskData = self.queue.get()           
                task=self.taskNumber
                self.taskNumber+=1
                currTime=t.time() 
                if taskData["method"]=="GET": 
                    r=requests.get(taskData["url"],headers=taskData["headers"])
                    delay=(t.time()-currTime)*1000               
                    #print("Task: ",task," Status Code: ",r.status_code," Time elapsed: %.3f"%(t.time()-self.startingTime), "s Delay: %.2f"%delay,"ms")
                    util.log("Task: {} Status Code: {} Delay: {}ms".format(task,r.status_code,delay))
                    self.queue.task_done() 
                elif taskData["method"]=="POST": 
                    r=requests.post(taskData["url"],headers=taskData["headers"],data=taskData["body"])
                    delay=(t.time()-currTime)*1000               
                    #print("Task: ",task," Status Code: ",r.status_code," Time elapsed: %.3f"%(t.time()-self.startingTime), "s Delay: %.2f"%delay,"ms")
                    util.log("Task: {} Status Code: {} Delay: {}ms".format(task,r.status_code,delay))
                    self.queue.task_done()
                elif taskData["method"]=="DELETE":
                    r=requests.delete(taskData["url"],headers=taskData["headers"],data=taskData["body"])
                    delay=(t.time()-currTime)*1000               
                    #print("Task: ",task," Status Code: ",r.status_code," Time elapsed: %.3f"%(t.time()-self.startingTime), "s Delay: %.2f"%delay,"ms")
                    util.log("Task: {} Status Code: {} Delay: {}ms".format(task,r.status_code,delay))
                    self.queue.task_done()
                else:
                    #print("ERROR: Unsuported method type : ",taskData["method"])
                    util.log("ERROR: Unsuported method type : {}".format(taskData["method"]))
                    self.queue.task_done()
                
            except Exception as e:
                print("Something went wrong! ",e)

    def setupWorkers(self,numOfWorkers):
        self.queue = Queue(numOfWorkers)
        for _ in range(numOfWorkers):
            thread = threading.Thread(target = self.connect)
            thread.daemon = True
            thread.start()
        #print("Workers added!")
        util.log("workerrs added!")
        self.setupAddingThread()


def run(file):
    r=Requester(file)
