#! /usr/bin/python -O
# -*- coding: UTF-8 -*-
# Cuesplit 2.0_pre1

import sys,re,time,shutil
from output import *

def countdown(seconds):
	sys.stdout.write(yellow("*")+" Proceeding in "+str(seconds)+" seconds, CTRL+C to interrupt... ")
	sys.stdout.flush()
	ticks = range(seconds)
	ticks.reverse()
	time.sleep(1)
	for i in ticks:
		sys.stdout.write(str(i+1)+" ")
		sys.stdout.flush()
		time.sleep(1)

def guess(): # Check the reliability of a cue file
	bad = 0 # 1 will stop the process and require --force
	secs = 0 # how many seconds to add to a 5 sec countdown
	quality = 0 # 0's no need to guess, 1's guess album name

	print ">>> Checking CUE quality..."
	if tracks != len(indexes):
		print red("*")+" Bad, it appears that there are missing indexes, I'm not gonna let it through."
		print yellow("*")+" 100% sure that the result will end up b0rked. May the --force be with you."
		bad = 1
		secs = 15
		guess = 2
	elif len(performers) == len(titles) == (len(indexes)+1):
		print green("*")+" Superb CUE :-) 100% sure it'll split OK"
		secs = 5
		guess = 0
	if len(performers) == len(titles) == (len(indexes)):
		print darkgreen("*")+" Album title and performer are missing."
		print yellow("*")+" Never mind, I can guess those from the filename... hopefully"
		secs = 7
		guess = 1
	if len(indexes) > len(titles):
		print red("*")+" Bad, it appears that some tags are missing, but the split shall proceed OK."
		print yellow("*")+" Expect b"+green(str(0))+"rked tags. Use the --force, Luke."
		bad = 1
		secs = 15
		guess = 2
	if len(performers) != len(titles):
		print red("*")+" Are you sure it's a cuefile ?? Or if it's Windows-made ?! Or maybe paw-written by a dog ??"
		print yellow("*")+" You should REALLY expect some seriously b"+red("0")+"rked tags, try --forcing it."
		bad = 1
		secs = 15
		guess = 2
	if secs == 0:
		print blue("*")+" Huh, I'm not sure if the file's good or bad ... spooky"
		print yellow("*")+" We got nothin' to loose, except of a few mins of CPU time, let's try it :o)"
		secs = 10
		guess = 0
	return [bad, secs, guess]

def ret_performer(cislo):
	try:
		return performers[cislo]
	except:
		return ""

def ret_title(cislo):
	try:
		return titles[cislo]
	except:
		return ""

def showlist():
	print ">>> It's gonna look like this:"
	seznam = []
	rozsah = range(tracks)
	if guess == 0:
		album = ret_performer(0)+" - "+ret_title(0)
		for track in rozsah:
			if track < 9:
				cislo="0"+str(track+1)
			else:
				cislo=str(track+1)
			seznam.append(cislo+": "+ret_performer(track+1)+green(" - ")+ret_title(track+1)+green(" - ")+indexes[track])
	else:
		album = re.findall('^[0123456789]*-(.+)\..', mediafile)[0]
		for track in rozsah:
			if track < 9:
				cislo="0"+str(track+1)
			else:
				cislo=str(track+1)
			seznam.append(cislo+": "+ret_performer(track)+green(" - ")+ret_title(track)+green(" - ")+indexes[track])
	print green("*")+" Album: "+album
	for line in seznam:
		print "   "+line
	print ">>> That'll be "+str(len(seznam))+" tracks. Feels fine ??"

def filerange(cislo):
	pole=[]
	for i in range(cislo):
		if i+1 < 10:
			pole.append("0"+str(i+1))
		else:
			pole.append(str(i+1))
	return pole

##
## Program runtime code begins somewhere in here :)
##

# test commandline args
try:
	if sys.argv[2] == "--force":
		override = 1
except:
	override = 0
try:
	cuefile_name = sys.argv[1]
except:
	print yellow("*")+" Usage: cuesplit file.cue [--force]"
	sys.exit(1)

# open file
print ">>> Opening and reading file..."
print yellow("*")+" CUE file to analyse: "+cuefile_name
try:
	cuefile = open(cuefile_name)
except:
	print red("*")+" Can't open file, permissions problem or file N/A"
	sys.exit(1)
cuefile_data = cuefile.read()

# extract mediafile
print ">>> Extracting the name of the file to split..."
try:
	media = re.findall('FILE "(.+)" (.+)', cuefile_data)[0]
	mediafile = media[0]
	mediatype = media[1].strip()
except:
	print red("*")+" Hahaha very funny, this ain't no cue."
	sys.exit(1)

# extract performers
print ">>> Extracting performers..."
performers = re.findall('PERFORMER "(.+)"', cuefile_data)

# extract titles
print ">>> Extracting titles..."
titles = re.findall('TITLE "(.+)"', cuefile_data)

# count tracks, just to be sure...
print ">>> Counting tracks..."
tracks = len(re.findall('TRACK (.+) AUDIO', cuefile_data))

# extract indexes and cat them together in a "xx:xx.xx xx:xx.xx xx:xx.xx" format (wavsplit reqs)
print ">>> Extracting split-times and building indexline..."
indexes = re.findall('INDEX 01 (.+)', cuefile_data)
indexline = ""
for index in indexes:
	part = re.findall('(.+):(.+):(.+)', index.strip())
	indexline = indexline+part[0][0]+":"+part[0][1]+"."+part[0][2]+" "
indexline = indexline.replace("00:00.00 ","") # no need to cut at 00:00
kvalita = guess()
bad = kvalita[0]
secs = kvalita[1]
guess = kvalita[2]

if bad == 0 or override == 1:
# show a niiice list "# performer - title - index"
	showlist()
	countdown(secs+5)
	print "\n>>> Now decoding "+teal(mediafile)+"..."
# and now code it to wav
	if mediatype == "MP3":
		print yellow("*")+" It's an mp3, using mpg123."
		medianame = re.findall('(.+).[mM][pP]3$',mediafile)[0]
		if os.system('mpg123 --wav \"'+medianame+'.wav\" \"'+mediafile+'\"') != 0:
			print red("\n*")+" Decode failed."
			sys.exit(1)
	elif mediatype == "OGG":
		print yellow("*")+" It's an ogg, decoding with oggdec."
		medianame = re.findall('(.+).[oO][gG][gG]$',mediafile)[0]
		if os.system('oggdec -o \"'+medianame+'.wav\" \"'+mediafile+'\"') != 0:
			print red("\n*")+" Decode failed."
			sys.exit(1)
	elif mediatype == "WAVE":
		print yellow("*")+" It's a wave, skipping decode."
		medianame = mediafile[:-4]
	print "\n>>> Splitting "+teal(cuefile_name)+"..."
	os.system('wavsplit \"'+medianame+'.wav\" '+indexline)
	os.chdir(medianame)
	soubory = os.listdir(".")
	soubory.sort()
	# count files... files should be == tracks
	if len(soubory) != tracks:
		print red("*")+" Aww, that's bad, it should split the file into "+str(tracks)+" tracks, but I see "+str(len(soubory))+" tracks :("
		sys.exit(1)
	print ">>> OKay, I'm ready to convert the files..."
 	countdown(5)
	frange = filerange(tracks)
	for i in range(tracks):
		try:
			retval = os.system("oggenc -q 5 \""+soubory[i]+"\" -a \""+ret_performer(i+1)+"\" -t \""+ret_title(i+1)+"\" -l \""+ret_title(0)+"\" -N \""+str(i)+"\" -o \""+frange[i]+" - "+ret_title(i+1).replace("/", "&")+".ogg\"") # replace slash with amp to avoid directory creation
			if retval == 0:
				os.remove(soubory[i])
			else:
				raise
		except:
			print "Packin up..."
			sys.exit(1)
	os.chdir("..")
	shutil.move(medianame, ret_performer(0)+" - "+ret_title(0))
	os.remove(medianame+".wav")
