#!/usr/bin/env python

import json

class Pathlist:
	DEFAULT_PRIORITY = 5
	persistent_pathlist = "PATHLIST"

	def __init__(self, pathfile, blacklist, workingdir, cont=True):
		self.paths = {}
		self.blacklist = blacklist
		self.workingdir = workingdir
		if not cont or not self.readStoredPaths():
			self.readInitialPaths(pathfile)

	def sync(self):
		self.writeStoredPaths()

	def readStoredPaths(self):
		try:
			f = open("%s/%s"%(self.workingdir, self.persistent_pathlist), "r")
			l = json.load(f)
			for path,priority in l:
				self.addPath(path,priority)

			return True
		except IOError:
			return False

	def writeStoredPaths(self):
		pl = []
		f = open("%s/%s"%(self.workingdir, self.persistent_pathlist), "w")
		for priority in self.paths:
			for path in self.paths[priority]:
				pl.append((path,priority))
		json.dump(pl, f)
		f.close()

	def readInitialPaths(self, pathfile):
		f = open(pathfile)
		for line in f:
			self.addPath(line.strip(), Pathlist.DEFAULT_PRIORITY)

	def getNext(self):
		return self.choosePath()

	def finished(self):
		for l in self.paths.values():
			if len(l) > 0:
				return False
		return True

	def addPath(self, path, priority):
		if self.blacklist.blacklisted(path):
			return

		if not self.paths.has_key(priority):
			self.paths[priority] = set()
		self.paths[priority].add(path)

	def delPath(self, path):
		for key in self.paths:
			self.paths[key].discard(path)

	def choosePath(self):
		keys = self.paths.keys()
		keys.sort()
		for key in keys:
			if len(self.paths[key]) > 0:
				return self.paths[key].pop()
		return None

