import sys, string, commands, struct, os, gdbm, whrandom,database
datafmt = '100s'
def getlist(mp3folder):
    listcommand = 'find  ' + mp3folder + ' -name *.mp3'
    output = commands.getoutput(listcommand)
    output = string.split(output, '\012') #break apart files at the newlines
    return output
def int_to_string(value):
    if value <= 0:
	value = '0'
    elif value == 1:
	value = '1'
    elif value == 2:
	value = '2'
    elif value == 3:
	value = '3'
    elif value == 4:
	value = '4'
    elif value == 5:
	value = '5'
    elif value == 6:
	value = '6'
    elif value == 7:
	value = '7'
    elif value == 8:
	value = '8'
    elif value == 9:
	value = '9'
    elif value >= 10:
	value = '10'
    return value

def addtostr(value):
    value = string.atoi(value)
    value = value + 1
    value = int_to_string(value)
    return value
def subfromstr(value):
    value = string.atoi(value)
    value = value - 1
    value = int_to_string(value)
    return value
def rebuild(db, mp3folder, programname, notfirsttime, spreadratings):
    if(notfirsttime == 0):
	count = 0
	output = getlist(mp3folder)
	length = len(output)
	if spreadratings == 1:
	    one = 1
	    two = 2
	    three = 3
	    four = 4
	    five = 5
	    six = 6
	    seven = 7
	    eight = 8
	    nine = 9
	    ten = 10
	    
	    q = 1
	    while count < length: #distribute the ratings over 1-5
		q = whrandom.randint(1,10)
		if q == 1:
		    if one <= 0:
			q = q +1
			continue
		    else:
			one = one - 1
		elif q == 2:
		    if two <= 0:
			q = q + 1
			continue
		    else: 
			two = two - 1
		elif q == 3:
		    if three <= 0:
			q = q + 1
			continue
		    else:
			three = three - 1
		elif q == 4:
		    if four <= 0:
			q = q + 1
			continue
		    else:
			four = four - 1
			
		elif q == 5:
		    if five <= 0:
			q = q + 1
			continue
		    else:
			five = five - 1
			
		elif q == 6:
		    if six <= 0:
			q = q + 1
			continue
		    else:
			six = six - 1
			
		elif q == 7:
		    if seven <= 0:
			q = q + 1
			continue
		    else:
			seven = seven - 1
			
		elif q == 8:
		    if eight <= 0:
			q = q + 1
			continue
		    else:
			eight = eight - 1
		
		elif q == 9:
		    if nine <= 0:
			q = q + 1
			continue
		    else:
			nine = nine - 1
		elif q == 10:
		    if ten <= 0:
			q = q + 1
			continue
		    else:
			ten = ten - 1
		if (one + two + three + four + five + six + seven + eight + nine + ten<= 0):
		    one = 1
		    two = 2
		    three = 3
		    four = 4
		    five = 5
		    six = 6
		    seven = 7
		    eight = 8
		    nine = 9
		    ten = 10
		q = int_to_string(q)
		output[count] = string.strip(output[count])
		datapack = struct.pack(datafmt, output[count])
		db[datapack] = q
		count = count + 1
	else:
	    while count < length:
		output[count] = string.strip(output[count])
		datapack = struct.pack(datafmt, output[count]) 
		db[datapack] = '10'
		count = count + 1
    if(notfirsttime):
	count = 0
	databasefile2 = os.environ['HOME'] + "/." + programname + "-2.db"
        try:
            db2 = gdbm.open(databasefile2, 'w')
        except:
            db2 = gdbm.open(databasefile2, 'c')
            
	output = getlist(mp3folder)
	while count < (len(output) - 1):           #make a blank database with the songs in mp3folder
	    output[count] = string.strip(output[count])
	    datapack = struct.pack(datafmt, output[count])
	    db2[datapack] = '10'
	    count = count + 1
	k = db.firstkey()
	while k != None:           #save the current values
	    keyvalue = db[k]
	    if(db2.has_key(k)):
		del db2[k]
		db2[k] = keyvalue
	    k = db.nextkey(k)
	db = db2
	k = db.firstkey()
        while k != None:
            songname = struct.unpack(datafmt, k)     #delte the songs that no longer exist
	    songname = songname[0]
            filename = string.replace(songname, '\000', '')
            status = commands.getstatus(filename)
	    q = string.find(status, 'No such file')
	    if(q != -1):  #if the string doesn't exist
		del db[k]
	    k = db.nextkey(k)
def makesetup(db, mp3folder,programname):
    "print a setup file in the format mp3file : value"
    k = db.firstkey()
    setupfile = os.environ['HOME'] + "/" + programname + ".setup"
    f = open(setupfile, "w")
    while k != None:
	songvalue = db[k]
	songname = k
	songname = string.split(songname, '\000')
	songname = songname[0]
	songname = string.strip(songname)
	printstring = songname + " : "
	printstring = printstring + songvalue2
	printstring = printstring + '\n'
	f.write(printstring)
	k = db.nextkey(k)
	
def setup(db, programname):
    "take the setup file and put that info into the database"
    setupfile = os.environ['HOME'] + "/" + programname + ".setup"
    try:
	f = open(setupfile, "r")
    except:
	print "oops, you forgot to run imp3 -m first!"
	sys.exit()
    data = f.read()
    data = string.split(data, '\n')
    datamax = len(data)
    del data[datamax - 1]            #get rid of the empty line at the end of data
    count = 0
    while count < datamax - 1:
	i = string.split(data[count], ":")
	imax = len(i)
	imax = imax - 1
	if imax == 1:
	    stringdata = i[0]
	elif imax > 1:
	    q = 0
	    stringdata = ""
	    while q < imax:
		if q == 0:                      #this deals with mp3s with a : in their name
		    stringdata = stringdata + i[q]
		else:
		    stringdata = stringdata + ':' + i[q]
		q = q + 1
	stringdata = string.strip(stringdata)
	namedata = struct.pack(datafmt, stringdata)
	value = string.atoi(i[imax])
	value = int_to_string(value)
	try:
	    del db[namedata]
	except:
	    pass
	db[namedata] = value
	count = count + 1
