# Bryan Schumaker (5 / 21 / 2011)

import os

import library
import track

stat = os.stat
walk = os.walk
join = os.path.join

Track = track.Track

def song_id(path):
	return stat(path).st_ino

def scan_path(path):
	file_map = dict()
	for root, dir, files in walk(path):
		for file in files:
			file = join(root, file)
			file_map[song_id(file)] = file
	return file_map

def rm_old_ids(old_ids, new_ids, tracks):
	to_remove = old_ids - new_ids
	for id in to_remove:
		del tracks[id]

def add_new_ids(old_ids, new_ids, tracks, file_map):
	to_add = new_ids - old_ids
	for id in to_add:
		try:
			fpath = file_map[id]
			tracks[id] = Track(fpath)
		except Exception, e:
			pass

def update_path(path, tracks):
	file_map = scan_path(path)
	old_ids  = set(tracks.keys())
	new_ids  = set(file_map.keys())

	rm_old_ids(old_ids, new_ids, tracks)
	add_new_ids(old_ids, new_ids, tracks, file_map)

def update():
	library.lock_library()
	for path, lib in library.lib_dict.iteritems():
		print "Updating path:", path
		update_path(path, lib)
		print "Done!"
	library.save()
	library.unlock_library()
