import time
import datetime
import simpleplugin



class accumulator(object):
    def __init__(self, precision, metrics):
        self.precision = precision
        self.metrics = metrics

    def addFields(self, measurement, fields, tags, tm = None):
        rounded = self.getTime(tm)
        m = simpleplugin.Metric(measurement, tags, fields, rounded)
        self.metrics.put(m)

    def addGauge(self, measurement, fields, tags, tm = None):
        rounded = self.getTime(tm)
        m = simpleplugin.Metric(measurement, tags, fields, rounded)
        
        self.metrics.put(m)

    def addCounter(self, measurement, fields, tags, tm = None):
        rounded = self.getTime(tm)
        m = simpleplugin.Metric(measurement, tags, fields, rounded)
        
        self.metrics.put(m)

    def addLog(self, measurement, fields, tags, content, line, tm = None):
        rounded = self.getTime(tm)
        m = simpleplugin.LogMetric(measurement, tags, fields, content, line, rounded)
        
        self.metrics.put(m)

    def addSummary(self, measurement, fields, tags, tm = None):
        rounded = self.getTime(tm)
        m = simpleplugin.Metric(measurement, tags, fields, rounded)
        
        self.metrics.put(m)

    def addHistogram(self, measurement, fields, tags, tm = None):
        rounded = self.getTime(tm)
        m = simpleplugin.Metric(measurement, tags, fields, rounded)
        
        self.metrics.put(m)

    def addError(self, err):
        if err is not None:
            # Implement error handling logic here
            pass

    def setPrecision(self, precision):
        self.precision = precision

    def getTime(self, t):
        #print('getTime t:', t.__class__, t)
        if t:
            timestamp = t[0]
        else:
            timestamp = time.time()
        rounded= int(timestamp*float(self.precision.microseconds)+0.5) /self.precision.microseconds

        return rounded

# Example usage:
# precision = datetime.timedelta(seconds=1)
# metrics_queue = Queue.Queue()  # Assuming Queue module is imported
# acc = accumulator(precision, metrics_queue)

# Use acc to add metrics, e.g., acc.AddFields(...)
def newAccumulator(precision, metrics):
    return accumulator(precision, metrics)