#!/usr/bin/python


import os, getpass, shutil

SpaceForPodcastsInMegabytes = 1000
ExcludedFileTypes = ['m4v']
LinuxPath = '/home/'+getpass.getuser()+'/Music/Podcasts/'


def getOSSpecificFilepath():
	if os.path.exists('/boot/grub'):
		return LinuxPath
	elif os.path.exists('/Users'):
		return '/Users/'+getpass.getuser()+'/Music/iTunes/iTunes Music/Podcasts/'
	elif os.path.exists(r'C:\\'):
		return 'C:\\Users\\'+getpass.getuser()+'\\music\\itunes\\itunes music\\podcasts\\'
	else:
		print 'problem getting os specific filepath'
	
def getDevicepath():
	if os.path.exists('/Volumes'):
		for item in os.listdir('/Volumes'):
			try:
				if 'BlackBerry' in os.listdir('/Volumes/'+item):
					volname = '/Volumes/'+item+'/BlackBerry/music/Podcasts/'
			except:
				continue
		try:
			return volname
		except NameError:
			return 'Device not found'
	elif os.path.exists(r'E:\\BlackBerry'):
		return r'E:\\BlackBerry\\music\\Podcasts\\'
	elif os.path.exists('/boot/grub'):
		for item in os.listdir('/media'):
			try:
				if 'BlackBerry' in os.listdir('/media/'+item):
					volname = '/Volumes/'+item+'/BlackBerry/music/Podcasts/'
			except:
				continue
		try:
			return volname
		except NameError:
			return 'Device not found'
	else:
		return 'Device not found'


def checkDevicepath():
	if not os.path.exists(getDevicepath()):
		os.mkdir(getDevicepath())

def allFiles(filepath, depth, flist=[]):
	fpath=os.walk(filepath)
	fpath=[item for item in fpath]
	while depth < len(fpath):
		for item in fpath[depth][-1]:
			flist.append(fpath[depth][0]+os.sep+item)
		depth+=1
	return flist

def getFilelist():
	a = getOSSpecificFilepath()
	b = allFiles(a, 1, [])
	return b

def getDevicelist():
	a = getDevicepath()
	b = os.walk(a)
	c = [item for item in b]
	return c[0][-1]

def getMtimeList(filelist):
	tmplist = []
	for item in filelist:
		tmplist.append(os.stat(item).st_mtime)
	return tmplist

def getMtimeDict(filelist):
	tmpdict = {}
	for item in filelist:
		tmpdict[os.stat(item).st_mtime] = item
	return tmpdict

def getUpdatedList(filelist, mtimelist, mtimedict):
	tmplist = []
	a = sorted(mtimelist)
	for item in a:
		tmplist.append(mtimedict[item])
	return tmplist

def defaultCast():
	a = getFilelist()
	b = getMtimeList(a)
	c = getMtimeDict(a)
	d = getUpdatedList(a, b, c)
	return d
	
def thoseThatFit(fulllist=defaultCast(), targetsize=SpaceForPodcastsInMegabytes*1000000):
	counter = -1
	tmplist = []
	tmpnum = 0
	while tmpnum < targetsize:
		if fulllist[counter][-3:] in ExcludedFileTypes:
			counter -= 1
			if abs(counter) >= len(fulllist):
				break
		else:
			tmplist.append(fulllist[counter])
			tmpnum += os.stat(fulllist[counter]).st_size
			if abs(counter) < len(fulllist):
				counter -= 1
			else:
				return tmplist
				break
	return tmplist


def cpFunction(dp=getDevicepath()):
	a = thoseThatFit()
	b = getDevicelist()
	c = [item.split(os.sep) for item in a]
	c = [item[-1] for item in c]
	counter=0
	for item in b:
		if item not in c:
			try:
				os.remove(dp+item)
				print 'removed', item
			except:
				continue
	while counter < (len(a)):
			if c[counter] in b:
				counter+=1
			else:
				print 'adding', a[counter], '...'
				shutil.copy2(a[counter], dp)
				counter += 1

if getDevicepath() != 'Device not found':
	checkDevicepath()
	cpFunction()
else:
	print 'Device not found'
