package org.btcollider.cnc.keysrv;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class KTConcierge implements Runnable {
	final Logger log = LoggerFactory.getLogger(KeyServer.class);
	
	private KeyTree keyTree;
	private long maxWorkSpan;
	
	public KTConcierge(KeyTree keyTree, long maxWorkSpan) {
		this.keyTree = keyTree;
		this.maxWorkSpan = maxWorkSpan;
	}
	
	@Override
	public void run() {
		recCheckInWork(keyTree);
	}

	private void recCheckInWork(KeyTree node) {
		if (node == null) return;
		
		if (node.inWork()) {
			long inWorkSpan = System.currentTimeMillis() - node.inWorkSince();
			if (inWorkSpan >= maxWorkSpan) {
				if (node.isLeaf()) {
					StringBuilder key = new StringBuilder();
					key.append(node.getValue() ? "1": "0");
					KeyTree parent = node.getParent();
					while (parent != null) {
						key.insert(0, parent.getValue() ? "1": "0");
						parent = parent.getParent();
					}
					log.debug("{}: Retracting Work for key {}, inWorkSince: {}", System.currentTimeMillis(), key, node.inWorkSince());
				}
				node.clearInWork();
			}
		}
		
		recCheckInWork(node.getLeft());
		recCheckInWork(node.getRight());
	}
}
