import collections
import time
import logging

circular = collections.deque(maxlen=80)
lastrider = None

def strtm(t=None):
    if t is None:
        t = time.time()
    tm = time.localtime(t)
    return time.strftime("%H:%M:%S",tm)[0:7] + ("%5.3f" % (t % 10))
    
class Rider(object):
    def __init__(self, name):
        self.name = name
        self.lastprompt = None
        self.cnt = 0
        self.lastline = None
        self.lasttime = 0

    def putlast(self):
        global lastrider, circular
        if self.lasttime != 0:
            circular.append("...")
            circular.append("%s %s %s %s" % (strtm(self.lasttime), self.name, self.lastprompt, self.lastline))
        self.cnt = 0
        self.lasttime = 0
        
    def put(self, prompt, line):
        global lastrider, circular
        now = time.time()
        if prompt != self.lastprompt or lastrider != self:
            if lastrider:
                lastrider.putlast()
            self.lastprompt = prompt
            lastrider = self
        else:
            if self.cnt >= 4:
                self.lastline = line
                self.lasttime = now
                return
            self.cnt += 1
        circular.append("%s %s %s %s" % (strtm(now), self.name, prompt, line))
    
def log():
    if lastrider:
        lastrider.putlast()
    for line in circular:
        logging.info("%s", line)
    circular.clear()
