import re


class bathook:
    def __init__(self, path_to_report, data_from):
        with open (path_to_report, "r") as messagesfile: # Open the file
            self.raw_messages = messagesfile.read() # Extract the data
        
        if "Rescheduled" in self.raw_messages: # If the job was rescheduled
            self.raw_messages = self.raw_messages.split("Rescheduled", 1)[-1] # Remove the failed data
            self.rescheduled = "\nJob was rescheduled at least once." # We rescheduled
        else:
            self.rescheduled = "" # We did not reschedule
        
        self.endtime = self.mextract(self.raw_messages, "End time:")
        self.elapsedtime = self.mextract(self.raw_messages, "Elapsed time:")
        self.byteswritten = self.mextract(self.raw_messages, "SD Bytes Written:")
        self.usedvolumes = self.mextract(self.raw_messages, "Volume name\(s\):")
        self.jobname = self.mextract(self.raw_messages, "Job:")
        self.jobid = self.mextract(self.raw_messages, "JobId:")
        self.data_from = data_from

        self.maxCharPerMessage = 1994
        
    def mextract(self, report, variable):
        try:
            result = re.search(variable + '(.*)', report)
            print(result)
            return(result.group(1).lstrip()) # lstrip removes leading spaces.
        except:
            return("[Variable Not found]")
    
    def get_formatted_message(self):
        if "Backup OK" in self.raw_messages and "Backup OK -- with warnings" not in self.raw_messages:
            truncated_stdout = ["""Job {0} (Job {1}) completed with status Backup OK, omitting full report.
All data from {2} was successfully written to tape on {3}.
Backup took {4} And used {5} bytes.""".format(self.jobname, self.jobid, self.data_from, self.endtime, self.elapsedtime, self.byteswritten)]
            if len(self.usedvolumes) > 1:
                truncated_stdout[0] = truncated_stdout[0] + ("\nWrote data to volume(s) {0} {1}".format(self.usedvolumes, self.rescheduled))
        else:
            # Discord limits each message to 2000 chars, if the message is longer than that, truncate it
            truncated_stdout = [cleaned_stdout[i:i+self.maxCharPerMessage] for i in range(0, len(cleaned_stdout), self.maxCharPerMessage)]
        return(truncated_stdout)