from PythonQt import *
import gettext

ALIGN_LEFT, ALIGN_CENTER, ALIGN_RIGHT = 0, 1, 2
VALIGN_TOP, VALIGN_CENTER, VALIGN_BOTTOM = 11, 12, 13

# debug = 1
debug = 0

# key define
OffHook = 'F3'
OnHook = 'F4'
Video = 'F7'
VideoPrivacy = 'F8' # later delete
VideoMute = 'F9'
key_favorite = 'WEB'
Camera =  'F10'
Transfer = 'INFORMATION'
Green = 'F5'
CLEAR = 'CLR'
Red = 'F6'
Menu1 = 'F1'
Menu2 = 'F2'
Menu3 = 'SOFT3'
Menu4 = 'SOFT4'

IMAGE = 0
TEXT = 1
RECT = 2
CALLBACK_KEY_UP = 0 
CALLBACK_KEY_DOWN = 0
CALLBACK_MOUSE_UP = 0
CALLBACK_MOUSE_DOWN = 0
INPUT_READ = 1
INPUT_WRITE = 2
INPUT_HUP = 8 

class CanvasItemWrapper(object):
        item = 0

        def __init__(self,item):
            self.item = item

	def type_get(self):
		return RECT

	def xy_set(self,x=0,y=0,w=0,h=0):
		return                                                  
        
        def move(self,x,y):
        	if (debug):
               		print 'move ', x, ' ', y 
                self.item.x = x
                self.item.y = y
 
        def show(self):
        	if self.item:
                    self.item.visible = 1
                
        def hide(self):
        	if self.item:
                    self.item.visible = 0

        def geometry_get(self):
                return [self.item.x,self.item.y,self.item.w,self.item.h]

	def geometry_set(self,geometry):
        	if (debug):
        		print 'set geometry ', geometry[0], ' ', geometry[1]
		self.item.x = geometry[0]
		self.item.y = geometry[1]
		self.item.w = geometry[2]
		self.item.h = geometry[3]

	geometry = property(geometry_get,geometry_set)
        
        def free(self):
                self.hide()
                if ( self.item != None ):
                	self.item.deleted = 1
                self.item = None

        def getfile(self):
                return self.item.file

        def setfile(self, file):
                if ( self.item != None ):
                    self.item.file = file

        file = property(getfile, setfile)
        
        def layer_get(self):
                return self.item.layer

        def layer_set(self, layer):
                self.item.layer = layer

        layer = property(layer_get, layer_set)

        def getpos(self):
                return self.item.x, self.item.y

        def setpos(self, pos):
        	if (debug):
        		print 'set pos ', pos[0], ' ', pos[1]
        	if self.item:
                    self.item.x = pos[0]
                    self.item.y = pos[1]

        pos = property(getpos, setpos)

        def text_get(self):
                return self.item.text

        def text_set(self, text):
                if ( self.item != None and self.item.text != text ):
	        	print 'text_set ', text
                	self.item.text = text

        text = property(text_get, text_set)

        def size_get(self):
                return self.item.w, self.item.h

        def size_set(self, w, h):
                self.item.w = w
                self.item.h = h

        def size_set2(self, size):
                self.item.w = size[0]
                self.item.h = size[1]

        size = property(size_get, size_set2)

	def color_get(self):
		return self.item.color
		
	def color_set(self,r=0,g=0,b=0,a=0):
		self.item.color = QColor(r,g,b,a)

	def color_set2(self,col=(0,0,0,0)):
		self.item.color = QColor(col[0],col[1],col[2],col[3])
		
	color = property(color_get, color_set2)
	
        def smooth_scale_set(self,x):
		return

	def fill_set(self,x,y,w,h):
		if debug:
			print 'fill_set ', x, ' ', y, ' ', w, ' ', h
		#print 'fill_set ', x, ' ', y, ' ', w, ' ', h
		self.item.fill_set(x,y,w,h)
		return
 
        def descent_get(self):
                return self.item.descent

        def horiz_advance_get(self):
        	if (debug):
        		print 'get horiz advance'
        	return self.item.horiz_advance

        def clip_set(self,clip):
                geo = clip.geometry
                self.item.clip = QRect(geo[0], geo[1], geo[2], geo[3])

        def resize(self,w,h):
        	self.item.resize(w,h)
        	
	def getfont(self):
		print 'getfont'
		return (self.item.fontFamily, self.item.fontPixelSize - 4)
		
	def setfont(self,font=('',13)):
		print 'setfont ', font[0], ' ', font[1]
		try:
			self.item.fontFamily = font[0]
			self.item.fontPixelSize = 4 + font[1]
		except:
			print '### set font problem'
		
	font = property(getfont,setfont)
		
	def font_set(self,fn,fs):
		print 'font_set'
		self.setfont((fn,fs))
		
	def font_get(self):
		print 'font_get'
		return self.getfont()

	def handle_key(self, down, key):
                if ( self.item != None ):
                     return self.item.handleKey(key, down)



class Evas:
	rec = ''
	test = 0
        itemList = [None,None]
        trans = gettext.NullTranslations()

	def __init__(self,x,y,w,h,r=0):
		if debug:
			print 'evas init'
                self.c = Canvas(x,y,w,h)
                self.c.connect('keyPressed(int)', self.keyPressed)
                self.c.connect('keyReleased(int)', self.keyReleased)
		self.tid = 1
		self.timer_cb_list = [ ]
		self.notifier_list = [ ]
		self.idle_cb_list = [ ]
		self.idle_timer = 0

        def keyPressed(self, key):
        	return self.internalHandleKey(key, True)

        def keyReleased(self, key):
        	return self.internalHandleKey(key, False)

        def internalHandleKey(self, key, state):
                if ( key == 114 ):
                    return self.handle_key(state, OffHook)
                elif ( key == 115 ):
                    return self.handle_key(state, OnHook)

                if ( key == 63 ):
                    return self.handle_key(state, Menu1)
                elif ( key == 64 ):
                    return self.handle_key(state, Menu2)
                elif ( key == 61 ):
                    return self.handle_key(state, Menu3)
                elif ( key == 62 ):
                    return self.handle_key(state, Menu4)
                
                elif ( key == 66 ):
                    return self.handle_key(state, Video)
                elif ( key == 88 ):
                    return self.handle_key(state, VideoPrivacy)
                elif ( key == 50 ):
                    return self.handle_key(state, VideoMute)
                
                elif ( key == 105 ):
                    return self.handle_key(state, 'Left')
                elif ( key == 106 ):
                    return self.handle_key(state, 'Right')
                elif ( key == 49 ):
                    return self.handle_key(state, 'OK')
                elif ( key == 103 ):
                    return self.handle_key(state, 'Up')
                elif ( key == 108 ):
                    return self.handle_key(state, 'Down')

                elif ( key == 68 ):
# shchun : change key value.                
#                    return runtime.evas.handle_key(state, config.key_favorite)
                    return self.handle_key(state, VideoPrivacy) 
                elif ( key == 120 ):
                    return self.handle_key(state, Camera)
                elif ( key == 51 ):
                    return self.handle_key(state, Transfer)
                    
                elif ( key == 65 ):
                    return self.handle_key(state, Green)
                elif ( key == 52 ):
                    return self.handle_key(state, CLEAR)
                elif ( key == 67 ):
                    return self.handle_key(state, Red)
                    
                elif ( key == 55 ):
                    return self.handle_key(state, '*')
                elif ( key == 74 ):
                    return self.handle_key(state, '#')
                elif ( key == 82 ):
                    return self.handle_key(state, '0')
                elif ( key == 79 ):
                    return self.handle_key(state, '1')
                elif ( key == 80 ):
                    return self.handle_key(state, '2')
                elif ( key == 81 ):
                    return self.handle_key(state, '3')
                elif ( key == 75 ):
                    return self.handle_key(state, '4')
                elif ( key == 76 ):
                    return self.handle_key(state, '5')
                elif ( key == 77 ):
                    return self.handle_key(state, '6')
                elif ( key == 71 ):
                    return self.handle_key(state, '7')
                elif ( key == 72 ):
                    return self.handle_key(state, '8')
                elif ( key == 73 ):
                    return self.handle_key(state, '9')

        	if debug:
        		print 'got key: ', key
        	print 'got key: ', key

	def pre_parse(self, str_textid):
                text = str_textid.replace( chr(3), '' )
                return self.trans.gettext(text)

	def image_cache_set(x,y):
		if debug:
			print 'image cache set'
		return

	def font_cache_set(x,y):
		if debug:
			print 'font cache set'
		return

	def font_path_prepend(self,dir_list):
		if debug:
			print 'font_path_prepend'
		return

	def image_cache_flush(self):
		if debug:
	 		print 'image cache flush'
		return

        def line(self,x=0,y=0,w=0,h=0,pos=(0,0),size=(0,0)):
		if debug:
		    print 'line'
        	return self.rectangle(x,y,w,h,pos,size)
        	
        def rectangle(self,x=0,y=0,w=0,h=0,pos=(0,0),size=(0,0)):
		if debug:
		    print 'rect'
		if ((x==0 and y==0) and (pos[0]!=0 or pos[1]!=0)):
                	rect = self.c.newRect(pos[0],pos[1],size[0],size[1])
                else:
                	rect = self.c.newRect(x,y,w,h)
                return CanvasItemWrapper(rect)

	def image(self,pos=(0,0),file=''):
		if debug:
		    print 'image'
		#print 'image ', pos[0], ' ', pos[1], ' ', file
                img = self.c.newImage(pos[0],pos[1],file)
                return CanvasItemWrapper(img)

	def event_set_mask(self,val):
		if debug:
			print 'event_set_mask'
		return

	def event_set_callback(self,cb):
		if debug:
			print 'event_set_callback'
		return

	def timeout_add(self,x,cb,args=None):
		if debug:
			print ' ** timeout_add, ', x, ' ', cb, ' ', args
		#print ' ** timeout_add, ', x, ' ', cb, ' ', args
		#for timer, c in self.timer_cb_list:
		#    if (c == cb):
		#    	if debug:
		#        	print 'timer already exists for ', cb
		#        self.timeout_remove(timer)
		#        break
		timer = Timer(x)
		timer.connect('timeout(Timer*)',self.call_timeout_cb)
		self.timer_cb_list.append((timer,cb,args))
		return timer

	def timeout_remove(self,tid):
		for timer, cb, args in self.timer_cb_list:
		    if (timer == tid):
		    	if debug:
				print ' ** timeout_remove, ', cb
			#print ' ** timeout_remove, ', cb
			self.timer_cb_list.remove((timer,cb,args))
			timer.stop()
			timer.deleteLater()
			timer = None
			return
			
	def call_timeout_cb(self,tid):
		for timer, cb, args in self.timer_cb_list:
			if (timer == tid):
				if debug:
					print ' ** timeout, ', cb
				#print ' ** timeout, ', cb
				x = 0
				if (args != None):
					x = cb(args)
				else:
					x = cb()
				if x in (0, False, None):
					self.timeout_remove(tid)
		return

        def text(self,text='',pos=(0,0),font=('',13),color=(255,255,255,255)):
                # print 'display text: ', text
                text = self.pre_parse(text)
                txt = self.c.newText(pos[0]+1,pos[1],text,font[0],font[1]+4,QColor(color[0],color[1],color[2],color[3]))
                return CanvasItemWrapper(txt)

        def OutlineLabelEx(self,text,font,pos,color,outline_color=None,align=ALIGN_CENTER,abbr_width=-1,valign=VALIGN_TOP):
                item = self.c.newOutlineLabelEx(text,font[0], font[1]+4,pos[0],pos[1],QColor(color[0],color[1],color[2],color[3]),QColor(outline_color[0],outline_color[1],outline_color[2],outline_color[3]),align,abbr_width,valign)
                return CanvasItemWrapper(item)

        def calendar(self):
                return Calendar(self.c.qwidget_cast())

	def uiloader(self):
		return QUiLoader(0)

	def canvas(self):
		return self.c.qwidget_cast()

	def widgetExample(self):
                print 'create widget example'
                return CanvasItemWrapper(self.c.newCalculator())

	def list(self,labels,pos=(119,54)):
		print 'create listwidget'
		return List(self.c.qwidget_cast(),labels,pos)

        def update(self, geo):
                #self.c.update(geo[0],geo[1],geo[2],geo[3])
                return

        def render(self):
        	if debug:
			print 'render'
		# self.c.render()
                return

	def render_now(self):
		if debug:
			print 'render now'
		self.c.processEvents()
		return

	def idle_add(self,cb,args=None):
		if debug:
			print 'idle_add'
		#print 'Adding idle callback: ', cb
		if (self.idle_timer):
			self.idle_timer.stop()
		else:
			self.idle_timer = QTimer()
			self.idle_timer.setSingleShot(1)
			self.idle_timer.setInterval(1)
			self.idle_timer.connect('timeout()',self.call_idle_cb)
		self.idle_timer.start()
		self.idle_cb_list.append((cb,args))

	def call_idle_cb(self):
		for cb,args in self.idle_cb_list:
			print 'Calling idle callback: ', cb
			if (args != None):
				cb(args)
			else:
				cb()
		self.idle_cb_list = []
		return

	def set_lang(self,lang):
                import gettext
		import os

		print 'set language to ', lang
                
                if ( lang == 'Korean' ):
                    os.environ["LC_ALL"] = 'es_ES'
                    os.environ["LANG"] = 'ko_KR'
                    # gettext.install('lgvp-ko', '/usr/local/lgvp/locale', unicode=False)
                    self.trans = gettext.translation("lgvp-ko", '/usr/local/lgvp/locale', languages=['es'])
                    self.trans.install()
                elif ( lang == "English" ):
                    os.environ["LC_ALL"] = 'C'
                    os.environ["LANG"] = 'C'
                    # gettext.install('lgvp', '/usr/local/lgvp/locale', unicode=False)
                    # trans = gettext.translation("lgvp", '/usr/local/lgvp/locale', languages=['C'], 
                    self.trans = gettext.NullTranslations()
                    self.trans.install()
                elif ( lang == "Norwegian" ):
                    os.environ["LC_ALL"] = 'no_NO'
                    os.environ["LANG"] = 'no_NO'
                    # gettext.install('lgvp', '/usr/local/lgvp/locale', unicode=False)
                    self.trans = gettext.translation("lgvp", '/usr/local/lgvp/locale', languages=['no'])
                    self.trans.install()
                else:
                    print 'unsupported language, edit evas.py to add ', lang

		return
                if ( lang == 'Korean' ):
                    os.environ["LANG"] = 'ko_KR'
                elif ( lang == "Spanish" ):
                    os.environ["LANG"] = 'es_ES'
                elif ( lang == "Portuguese" ):
                    os.environ["LANG"] = 'pt_PT'
                elif ( lang == "Russian" ):
                    os.environ["LANG"] = 'ru_RU'
                elif ( lang == "English" ):
                    os.environ["LANG"] = 'C'
                elif ( lang == "Italian" ):
                    os.environ["LANG"] = 'it_IT'
                elif ( lang == "Deutsch" ):
                    os.environ["LANG"] = 'de_DE'
                elif ( lang == "Francais" ):
                    os.environ["LANG"] = 'fr_FR'
                elif ( lang == "Spain" ):
                    os.environ["LANG"] = 'es_ES'
                if debug:
                	print os.environ["LANG"]
		print 'set language to ', os.environ["LANG"]
#                translator.load()

        def use_transparency(self, flag):
                import os
                if debug:
                        print 'use transparency'
		#print 'use transparency ', flag
                #self.c.setTransparency(flag)
                #self.c.render()
                return
#		if (flag == True):
#			os.system("fb0top 0")
#		else:
#			os.system("fb0top 1")
#		return
       
	def loop(self):
		if debug:
			print 'loop'
		return

	def quit(self):
		if debug:
			print 'quit'
		self.c.deleteLater()
		return

	def input_add(self,fd,type,cb):
		if debug:
			print 'input add'
		#print 'input add ', cb
		for n,c in self.notifier_list:
		   if (n.fd() == fd):
		       #if (cb == c):
		        	print 'socket notifier is already created for socket ', fd 
		        	return
		       
		if (type == INPUT_READ):
		    notifier = SocketNotifier(fd, 2)
		else:
		    print 'socket notifier type not supported'
		notifier.connect('activated2(int,int)', self.input_cb)
		
		self.notifier_list.append((notifier,cb))
		return notifier	
	
	def input_cb(self,fd,type):
		import socket
		#print 'got input callback: ', fd, type
		for n, c in self.notifier_list:
			if (n.fd() == fd):
				#print 'calling callback: ', c
				if ( type == 2 ):
					c(fd,INPUT_HUP)
				else:
					c(fd,INPUT_READ)
	
	def input_remove(self,notifier):
		for n, c in self.notifier_list:
			if (n == notifier):
				self.notifier_list.remove((n,c))
				notifier.deleteLater()
				notifier = None


