# coding=utf8

import socket, time, sys
from d import D
from parms import Parms

class Meter():

	def __init__(self, d):
		self.d = D("{}, troughput measuring daemon".format(d.debid))

	def run(self):
		self.d.log("started", sev=3)
		ssc, sc = None, None
		ssc = self.bindwait('', Parms.baseport)
		try:
			while True:
				self.d.log("accepting...", sev=3)
				sc = ssc.accept()[0]
				self.d.log("accepted", sev=3)
				n1 = 0
				n0 = len(sc.recv(16 * 1024))
				while n0 > 0:
					n1 = n1 + n0
					if self.d.ll(5): self.d.log("n0={}, n1={}".format(n0, n1))
					if n1 >= 16 * 1024:
						if self.d.ll(5): self.d.log("{} received, sending acknoledgement".format(n1))
						sc.send(bytes("=>{:08d}".format(n1), "utf8"))
						n1 = 0
					n0 = len(sc.recv(16 * 1024))
				sc.close()
		except KeyboardInterrupt:
			pass
		except Exception as e:
			self.d.abendMsg("measuring", e=e)
		self.d.log("closing ssc...", sev=4)
		if sc: sc.close()
		if ssc: ssc.close()

	def bindwait(self, host, port):
		ssc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		while True:
			try:
				ssc.bind((host, port))
				break
			except Exception as e:
				if e.strerror == "Address already in use":
					self.d.log("Address {}:{} already in use, waiting 10 secs...".format(host, port))
					time.sleep(10)
					continue
				self.d.abend("bind", e)
				sys.exit(1)
		ssc.listen(1)
		self.d.log("bound to {}:{}".format(host, port), sev=2)
		return ssc