from threading import Thread, Event
import os
import csv, zlib,time
import base64


##Class to handle auto save
class Autosaveclas(Thread):
    def __init__(self,handlingoutput):
        self._handlingoutput = handlingoutput
       
        Thread.__init__(self)
        self._stop = Event()

    def run(self):
        
        #self._handlingoutput = handlingoutput
        while not self.stopped():
            if self._handlingoutput.Autosavechecker == True:
        
                if os.path.isdir(str(self._handlingoutput.path)):

                    if self._handlingoutput.logTable.getRowCount() > 0:
                        #self.path = fileLoad.getPath()
                        fname = "APIMapper"+"."+"csv"
                        fnameWithPath = os.path.join(self._handlingoutput.path,fname)
                        if os.path.exists(fnameWithPath):
                            os.remove(fnameWithPath)
                        self._handlingoutput.callbacks.printOutput("Saving the API Mapper output")
                        with open(fnameWithPath, 'wb') as loggerdata:
                            writer = csv.writer(loggerdata)
                            for logEntry in self._handlingoutput._log:
                                writer.writerow([str(logEntry._sr), str(logEntry._url) ,str(logEntry._method) , base64.b64encode(zlib.compress(logEntry._postbody.encode('utf-8'))) ,str(logEntry._FunctionalityName) , base64.b64encode(zlib.compress(logEntry._requestResponse.encode('utf-8'))) ,str(logEntry._TestCases), base64.b64encode(zlib.compress(logEntry._response.encode('utf-8'))) ,str(logEntry._status)])
                                 
                            loggerdata.close()
                    else:
                        self._handlingoutput.callbacks.printOutput("Skipping the API Mapper, Table is empty")
                    if self._handlingoutput.dataModel2.getRowCount() > 0:
                        fname2 = "Vulnerability"+"."+"csv"
                        fnameWithPath2 = os.path.join(self._handlingoutput.path,fname2)
                        if os.path.exists(fnameWithPath2):
                            os.remove(fnameWithPath2)
                        self._handlingoutput.callbacks.printOutput("Saving the Vulnerability output")
                        totalrow = self._handlingoutput.dataModel2.getRowCount()   
                        with open(fnameWithPath2, 'wb') as vulnerabilitydata:
                            writer = csv.writer(vulnerabilitydata)
                            for row in range (0, totalrow):
                                url = self._handlingoutput.dataModel2.getValueAt(row,0)
                                paramter = self._handlingoutput.dataModel2.getValueAt(int(row),1)
                                Vulnerability = self._handlingoutput.dataModel2.getValueAt(int(row),2)
                                Severity = self._handlingoutput.dataModel2.getValueAt(int(row),3)
                                Request = self._handlingoutput.dataModel2.getValueAt(int(row),4)
                                Response = self._handlingoutput.dataModel2.getValueAt(int(row),5)
                                #self.callbacks.printOutput(str(url))
                            
                            #self.callbacks.printOutput(str(logEntry._sr))
                                writer.writerow([str(url), str(paramter) ,str(Vulnerability),str(Severity),base64.b64encode(zlib.compress(Request.encode('utf-8'))),base64.b64encode(zlib.compress(Response.encode('utf-8')))])
                            vulnerabilitydata.close()
                    else:
                        self._handlingoutput.callbacks.printOutput("Skipping the  Vulnerability, Table is empty")
                else:
                    self._handlingoutput.autosavepath.setText("Output Directory doesn't exist")
                time.sleep(int(self._handlingoutput.time) * 60)

    def stop(self):
        self._stop.set()

    def stopped(self):
        return self._stop.isSet()