import config
class Log:
	def __init__(self):
		self.is_open = False
		self.type = type
		self.logs = []

		try:
			for l in open(config.log_file):
				l = l.strip()
				if len(l) < 20:
					continue
				ts = l[:19]
				log = l[20:]
				self.logs.append((ts, log))
		except IOError:
			pass

	def save(self):
		num_inc = 0
		num_out = 0

		skip = False
		f = open(config.log_file, 'w')
		for ts, log in self.logs:
			if log.startswith('--'):
				skip = False
				if log.startswith('-- incoming'):
					num_inc += 1
					if num_inc > 2:
						skip = True
				elif log.startswith('-- outgoing'):
					num_out += 1
					if num_out > 2:
						skip = True
				else:
					pass

			if skip:
				continue
			f.write('%s %s\n' % (ts,log))

	def open(self, type):
		#assert self.is_open == False
		if self.is_open:
			return
		self.type = type
		self.is_open = True
		self.log('++ %s call started' % type)

	def close(self):
		#assert self.is_open == True
		if not self.is_open:
			return
		self.is_open = False
		self.log('-- %s call ended' % self.type)
		self.save()

	def log(self, m):
		import time, ntptime
		ts = '%04d.%02d.%02d %02d:%02d:%02d' % \
			time.localtime(ntptime.ntime())[:6]

		#assert m
		self.logs.insert(0, (ts, m))

