""" Prepo module
"""

import os
from MiscFunctions import *

class Prepo(Testable):

    def __init__(self, prepoDir, rulesFile, testable):
        Testable.__init__(self,testable.id)
        self.testable = testable
        self.prepoDir = prepoDir
        self.rulesFile = rulesFile

    def requiredBinaries(self):
        return [self.prepoDir + '/prepo'] + self.testable.requiredBinaries()

    def requiredFiles(self):
        return ['%s/%s' % (self.prepoDir, self.rulesFile)] + self.testable.requiredFiles()

    def proverStatsForBatch(self, batch):
        return self.testable.proverStatsForBatch(batch)

    def hasPreprocessor(self):
        return True

    def preprocessorStatsForBatch(self, batch):
        return Testable.proverStatsForBatch(self, batch)

    def newStatistics(self):
        return PrepoStatistics()

    def addNewStatsToBatch(self, batch):
        Testable.addNewStatsToBatch(self,batch)
        self.testable.addNewStatsToBatch(batch)

    def addNewColumnToStatsFor(self, batch):
        Testable.addNewColumnToStatsFor(self, batch)
        self.testable.addNewColumnToStatsFor(batch)

    def parseOutputFilesFor(self, batch, testFile):
        self.testable.parseOutputFilesFor(batch, testFile + ".after_prepo")
        stats = self.preprocessorStatsForBatch(batch)
        stats.parseTime(testFile + '.prepo.time')

    def run(self, batchDir, testFile, timeout):
        prepocessedFile = testFile + ".after_prepo"
        self.runPrepo(batchDir, testFile, prepocessedFile)
        # Warning, total execution time (prepo + testable) might be
        # exceeding the maximum timeout!
        self.testable.run('.', prepocessedFile, timeout)

    def runPrepo(self, batchDir, testFile, prepocessedFile):
        initialDir = os.getcwd()
        chdirOrDie(self.prepoDir)

        timeArgs        = ["-p"]
        timeResponse    = '"%s/%s.prepo.time"' % (initialDir, testFile)
        prepoCmdLine    = ['"%s/prepo"' % self.prepoDir,
                           '"%s"' % self.rulesFile,
                           '"%s/%s"'   % (batchDir, testFile),
                           '"%s/%s"' % (initialDir, prepocessedFile)]

        systemOrDie("time", timeArgs + prepoCmdLine, stdout = timeResponse, stderr = timeResponse)
        chdirOrDie(initialDir)

    def getConfiguration(self):
        return [("Preprocessor", "prepo"),
                ("Version", "1"),
                ("Rules", self.rulesFile)] + self.testable.getConfiguration()


class PrepoStatistics(Statistics):

    def parseTime(self, timeResponseFile):
        # Skip the number of rules output
        self._parseTimeSkipping(1, timeResponseFile)
