# global variables used over the entire deplyer project
import os
import platform

class progressLog:

    # a log file dedicated to providing details to the web installer
    # about our progress though a task.
    #
    # format of the file is
    #
    #   Event|Result
    #
    #   Event is any human readble string not containing a |
    #   Result is
    #       Success     to indicate event was a success
    #       Warn:Text   to indicate success with a warning
    #                   Text indicates human readable warning not containing a |
    #       Fail:Text   to indicate failure of the event
    #                   Text indicates a human readable fail reason not containing a |
    #
    #   Each event is a single line.
    #
    #   Begins with the event Initializing|<init result>
    #   Ends with the event Complete|<overall result>
    #

    # log file object
    ld=0

    # have we opened an event?
    eventOpen=False

    def __init__(self,logFileName):
        # request no buffering on this file - what we write goes straight to
        # the disk to expedite getting it into the web interface for display.

        if platform.system() == "Linux":
            baseFolder="/root/cms-cloud-install/log"
        else:
            baseFolder="C:\\GitProjects\\cms-cloud-install"

        self.ld=open(os.path.join(baseFolder,logFileName),'w',0)

    def openEvent(self,eventName):
        # open a new event.

        # if an event is already open - close it with unknown.

        if self.eventOpen:
            # then close it.
            self.closeWarn("Unknown Result")

        self.ld.write(eventName)
        self.eventOpen=True

    def closeWarn(self,warningText):
        # close an open event with a warning

        if not self.openEvent:
            # humm.. what are you trying to close?
            self.openEvent("Unknown")

        self.ld.write("|Warn:"+warningText+os.linesep)
        self.eventOpen=False

    def closeSuccess(self):
        # close an open event with success

        if not self.openEvent:
            # humm.. what are you trying to close?
            self.openEvent("Unknown")

        self.ld.write("|Success"+os.linesep)
        self.eventOpen=False

    def closeFail(self,failText):
        # close an open event with failure. :(

        if not self.openEvent:
            # humm.. what are you trying to close?
            self.openEvent("Unknown")

        self.ld.write("|Fail:"+failText+os.linesep)
        self.eventOpen=False


    def closeLog(self):
        # shutdown.
        if self.eventOpen:
            # close unknown status
            self.closeWarn("Unknown Result")

        self.ld.close()

