import appuifw
import e32
import os
from graphics import *
from key_codes import *
import pymodlib

SCRIPT_LOCK = e32.Ao_lock()

end = False 
muzpath="e:\\MODS\\MODs\\"
manualplay = False
autoplay = True
current = -1	
dwi = None
scurrent=0
pgc=0
status="idle ..."
volume=0
 
class Drawable(object):
      def __init__(self):
	self.img = None;
	self.textrect=None;
	self.desc = "Drawable"
	self.sz=None
	self.textrect2=None
	self.bgcolor=0x000000
	self.txtcolor=0x00ff00
	self.boxcolor=0xff0000
	self.selcolor=0xffffff
	self.selactive=0xff0000
	self.dispcolor=0xff8000
	self.listfont='annotation'
	self.dispfont='title'
	self.items=[]

def drawtext(dw,x,y,col,strx,tfont):	
	dw.img.text((x,y),unicode(strx),fill=col,font=tfont)

def draw(dw):
	global scurrent	
        global pgc
	global current
	global status

	dw.img.clear(dw.bgcolor)
        if dw.items==None or len(dw.items)<1: 
		return
	poff=4	
	x=0
        y=-dw.textrect[1]
	y2=-dw.textrect2[1]
	yof=y+1
	
	dw.img.rectangle((x,0,dw.sz[0],yof+(yof*3)),width=1,outline=dw.boxcolor)
	cdesc= dw.items[current]	
	drawtext(dw,x,y2*1.25,dw.dispcolor,cdesc,dw.dispfont)
	drawtext(dw,x,y*3.5,dw.dispcolor,status,dw.listfont)

	y+=yof*poff
	c=dw.sz[1]/yof
	c=c-poff
	pgc=c
	offset=0

	i=int(scurrent/pgc)*pgc
	j=0
        while j<pgc and i<len(dw.items):	
		col = dw.txtcolor		
		if i==scurrent:
			col=dw.selcolor
		elif i==current:
			col=dw.dispcolor
		drawtext(dw,x,y,col,str(i)+" - "+dw.items[i],dw.listfont)
		y+=yof
		i=i+1
		j=j+1
	appuifw.app.body.blit(dw.img)
	
def redrawcallback(self,aRect=None):	
	global dwi
	if dwi!=None and dwi.img!=None:	 
		draw(dwi)

def eventcallback(a):
   global dwi
   global scurrent
	
#   print a

   if a['type']!=1:
	return
   
   key = a['scancode']
   if key==17 or key==57: #down, #9
      scurrent=scurrent+1
      if scurrent>len(dwi.items)-1:
	scurrent=len(dwi.items)-1	
      if key==57:
	next()

   elif key==16 or key==55: #up, #7
      scurrent=scurrent-1
      if scurrent<0:
	scurrent=0
      if key==55:
	prev()

   elif key==14: #left
	npg=int(scurrent/pgc)
	npg=npg-1
	if npg<0:
		npg=0
	scurrent=npg*pgc
   elif key==15: #right
	npg=int(scurrent/pgc)
	npg=npg+1
	if scurrent*npg>len(dwi.items)-1:
		npg=npg-1
	scurrent=npg*pgc	
   elif key==167: #middle
        itemcallback() 
   elif key==49: #1
	voldown()
   elif key==51: #3
	volup()
   
   draw(dwi)

def init(dw):
	sz = appuifw.app.body.size	
	dw.sz = sz	
	dw.img=Image.new((sz[0],sz[1]))	
	dw.textrect=dw.img.measure_text(u'Abcdefg', font=dw.listfont)[0]
	dw.textrect2=dw.img.measure_text(u'Abcdefg', font=dw.dispfont)[0]		
        print dw.textrect
	draw(dw)

def __exit__( ):
  global end
  end = True
  stop()
  pymodlib.Cleanup()
  SCRIPT_LOCK.signal( )

def updatestatus(desc):
	global status	
	global dwi
	global current	
	status = desc+ "... "+str(current)+"        vol: "+str(volume)
	draw(dwi)

def playitem(i):
	global dwi
	global current
	global scurrent
	scurrent=current
	path = dwi.items[i]
	updatestatus("playing")
	pymodlib.Load(muzpath+path)
	pymodlib.Play()
	  
def playnext():
    global current
    global dwi 
    current = current +1 
    if current>len(dwi.items)-1:	
	current = 0
    playitem(current)	

def playprev():
    global current
    global dwi
    current = current -1 
    if current<0:	
	current = len(dwi.items)-1
    playitem(current)	
    	
def stop():
	global dwi 		
	pymodlib.Stop()
	updatestatus("stopped")
	
def pause():
	global dwi	
	pymodlib.Pause()
	updatestatus("paused")

volume = 10
def volup():
    global dwi
    global volume
    volume=volume+10
    if volume>100:
	    volume = 100
    pymodlib.SetVolume(volume)
    updatestatus(">>")
    
def voldown():
    global volume
    global dwi
    volume=volume-10
    if volume<0:
	    volume = 0
    pymodlib.SetVolume(volume)
    updatestatus("<<")

def itemcallback():
	global scurrent	
	global current
	global manualplay
	manualplay=True
	current = scurrent
	playitem(current)
		
def loaddir(thepath):		
	global dwi
	titems = os.listdir(thepath)
	dwi.items=[]
	allowd = ".mod .it .s3m .sid .xm"
	for t in titems:
		tc = t.lower()
		if tc.endswith(".mod") or tc.endswith(".it") or tc.endswith(".s3m") or tc.endswith(".xm") or tc.endswith(".sid"):
			dwi.items.append(unicode(tc))

	
def check_msg(filename):
   msg=""
   if os.path.exists(filename):
	tfile = open(filename,'r')
	msg = tfile.readline();
	msg = unicode(msg)
	tfile.close();
	os.unlink(filename)
   try:
   	v = int(msg)
   except:
	v=-1   
   return v
 
def prev():
	global manualplay
	manualplay=True
	playprev()	

def next():
	global manualplay
	manualplay=True
	playnext()	

def about():
   appuifw.note(u"pymuz: voidonic@gmail.com (c) 2008", "info")	
	
def browse():
    global muzpath
    global dwi
    global current
    global scurrent
    global manualplay
   
    pdir = "e:\\MODS\\"   
    titems = os.listdir(pdir)
    uitems=[]
    for t in titems:
	if os.path.isdir(pdir+t):
		uitems.append(unicode(t))  
    index = appuifw.selection_list(uitems)
    if index != None:
		pdir = pdir+uitems[index]	
    		muzpath = pdir+"\\"
    		loaddir(pdir)
		manualplay=True
		scurrent=0
		current=-1
		playnext()
    draw(dwi)
       

appuifw.app.body = appuifw.Canvas(redraw_callback = redrawcallback,event_callback=eventcallback)
appuifw.app.screen = 'full'

dwi = Drawable()

appuifw.app.exit_key_handler = __exit__
appuifw.app.title= u'pymuz'
appuifw.app.menu = [(u'Browse', browse),(u'Play/Pause', pause),(u'Stop', stop), 
(u'Vup', volup),(u'Vdown', voldown),(u'About', about)]

init(dwi)

browse()
draw(dwi)
		
volume = pymodlib.GetVolume()				

while not end:
  r=pymodlib.IsPlaying()
  if r!=None and r==0 and autoplay:
  	if not manualplay:  
		playnext()
	else:
		while r==0:
		   r=pymodlib.IsPlaying()
		   e32.ao_sleep(1)		
		manualplay=False
#  print str(autoplay)+":"+str(r)
  e32.ao_sleep(1)	

SCRIPT_LOCK.wait()
