Newer
Older
Import / projects / LGN-IP3870 / t / orig / eaHandler.py
import runtime
from runtime import mmiDebug as MD 
from mmiSoundPath import Device, SP_State, SP_Context
import status
import os
import config
from vmHandler import VmHandler
from basemodel import NotifyStage
import ntptime

from setting import setting

class ExternalApplication:
	def __init__(self):
		self.inUse = None

	def getName(self):
		return self.name

	def mmiKeyBlock(self):
		MD.mmiTrace('MMI key close')
		status.MMI_KEY_BLOCK = True

	def mmiKeyUnblock(self):
		MD.mmiTrace('MMI key open')
		status.MMI_KEY_BLOCK = False

	def vmKeyBlock(self):
		MD.mmiTrace('VM key close')
		runtime.vmHandler.VM_KEY_STOP()

	def vmKeyUnblock(self):
		MD.mmiTrace('VM key open')
		runtime.vmHandler.VM_KEY_START()

	def browserKeyBlock(self):
		pass

	def browserKeyUnblock(self):
		pass

	def pause(self):
		pass
		
	def stop(self):
		self.pause()
		
	def setTerminalInformation(self):
		from vdcisetting import vdci_setting
		import profile

		import phonesetting
		terminalIp = '0.0.0.0'
		terminalIpInfo = phonesetting.getIpAddress()
		if terminalIpInfo:
			terminalIp = terminalIpInfo[0]
		
		telephoneNumber = vdci_setting.tel_num
		domain = vdci_setting.domain
		password = setting.pin

		if profile.profile.get_profile() == 2:
			if status.wifi_connected:
				connection = '1' #success
			else:
				connection = '0' # fail
		else:
			if status.LanConnected:
				connection = '1'
			else:
				connection = '0'
	
		#register_status = str(status.registered_status) #success -1 / fail -0
		import ntptime
		ntpTime = ntptime.timediff()
		self.regi_status = True
		
		# for key tone
		#keytone profile index/keytone volume/효과음 profile index/효과음 volume 
		buttonIndex = setting.button_effect_index # 0 해제 (1~4)
		effectIndex = setting.setting_effect_index # 0 해제  (1~3)
		buttonVolume = config.keytone[setting.keytone_volume-1]
		effectVolume = config.effect_sound[setting.effect_volume-1]

		runtime.vmHandler.VM_TERMINAL_INFO_SET(terminalIp, telephoneNumber, domain, password, connection, ntpTime, buttonIndex, buttonVolume, effectIndex, effectVolume)


class BankingClient(ExternalApplication):
	name = 'BANKING'
	
	def __init__(self):
		ExternalApplication.__init__(self)
		self.bankInUse = False
	
	def show(self):
		MD.mmiTrace('>>>>>>>>>>>> BankingClient SHOW')
		#runtime.vmHandler.EVT_APP_SET_FOREGROUND(EaHandler.BANKING)
		os.system('fbtop 3')

	def pause(self):
		# for dect
		if runtime.dectCallManager.isSubcribedDect():
			from dectConfig import MessageCode
			runtime.dectCallManager.sendVideophoneStatusReportToDect(MessageCode.VP_STATUS.IDLE)
		
		import os
		os.system("unmount /proc/bus/usb ");
		os.system("echo 0 > /proc/sys/lvp3870/usb_uart_switch ");
		
		self.vmKeyBlock()
		#runtime.vmHandler.EVT_APP_PAUSE()
		runtime.vmHandler.EVT_APP_MIDLET_PAUSE('BANKING')
		runtime.vdci_send_mesg(code1=config.MESG_BANKING, code2=config.MESG_BANKING_INFO, mesg1='0')
		self.bankInUse = False
		
	def resume(self, delayedShow=False):
		# for dect
		if runtime.dectCallManager.isSubcribedDect():
			from dectConfig import MessageCode
			runtime.dectCallManager.sendVideophoneStatusReportToDect(MessageCode.VP_STATUS.BANKING)
	
		import os
		#os.system("mount -t usbfs usbfs /proc/bus/usb ");
		#os.system("echo 1 > /proc/sys/lvp3870/usb_uart_switch ");	
		
		self.vmKeyUnblock()
		self.setTerminalInformation()
		#runtime.vmHandler.EVT_APP_RESUME()
		runtime.vmHandler.EVT_APP_MIDLET_RESUME('BANKING', setting.lang)
		runtime.vdci_send_mesg(code1=config.MESG_BANKING, code2=config.MESG_BANKING_INFO, mesg1='1')
		self.bankInUse = True
		
		if delayedShow:
			return 'BANKING'
		else:
			self.show()

	def start(self, sendMessage=False):
		pass
		
class MmsClient(ExternalApplication):
	name = 'MMSC'
	
	def __init__(self):
		ExternalApplication.__init__(self)
	
	def show(self):
		MD.mmiTrace('>>>>>>>>>>>> MmsClient SHOW')
		#runtime.vmHandler.EVT_APP_SET_FOREGROUND(EaHandler.MMSC)
		os.system('fbtop 3')

	def pause(self):
		runtime.SP_context.SP_stereoStopPlayback()
		#runtime.vmHandler.EVT_APP_PAUSE()
		runtime.vmHandler.EVT_APP_MIDLET_PAUSE('MMSC')
		self.vmKeyBlock()
		
	def pauseAck(self):
		self.vmKeyBlock()

	def resume(self, delayedShow=False):
		runtime.SP_context.SP_stereoPlayback()
		runtime.vmHandler.EVT_APP_MIDLET_RESUME('MMSC', setting.lang)
		self.vmKeyUnblock()
		self.setTerminalInformation()
		#runtime.vmHandler.EVT_APP_RESUME()

		if delayedShow:
			return 'MMSC'
		else:
			self.show()

	def start(self, sendMessage=False):
		pass

	def sendPhonebookData(self, phonebookList):
		info = 'phonebook://'
		#itemList = []
		#for item in phonebookList:
		#	itemList.append(item[0] + '&' + item[1])
		#info = info + ';'.join(itemList)
		number = phonebookList[0]
		name = phonebookList[1]
		info = info + number + '&' + name
		
		from vmHandler import VmHandler
		runtime.vmHandler.EVT_APP_MESSAGE(VmHandler.MMSC, info)

class MultimediaPlayer(ExternalApplication):
	name = 'MULTIMEDIA'
	
	def __init__(self):
		ExternalApplication.__init__(self)

	def show(self):
		MD.mmiTrace('>>>>>>>>>>>> MultimediaPlayer SHOW')
		#runtime.vmHandler.EVT_APP_SET_FOREGROUND(EaHandler.MULTIMEDIA)
		os.system('fbtop 3')

	def pause(self):
		runtime.SP_context.SP_stereoStopPlayback()
		#runtime.vmHandler.EVT_APP_PAUSE() #delete
		#runtime.vmHandler.EVT_APP_MIDLET_PAUSE(self.name)
		runtime.vmHandler.EVT_APP_MIDLET_PAUSE('MULTIMEDIA')
		self.vmKeyBlock()
		#import time
		#time.sleep(1)

	def resume(self, delayedShow=False):
		if delayedShow:
			return 'MULTIMEDIA'
		else:
			self.show()
	
		runtime.mmedia.unload()
		runtime.SP_context.SP_stereoPlayback()
		#runtime.vmHandler.EVT_APP_RESUME()  # delete
		#runtime.vmHandler.EVT_APP_MIDLET_RESUME(self.name)
		runtime.vmHandler.EVT_APP_MIDLET_RESUME('MULTIMEDIA', setting.lang)
		runtime.vmHandler.EVT_APP_SET_FOREGROUND(EaHandler.MULTIMEDIA)
		
		self.vmKeyUnblock()
		self.setTerminalInformation()
		
			
	def play(self):
		self.resume()
		runtime.vmHandler.EVT_APP_MIDLET_RESUME('MULTIMEDIA', setting.lang)
		runtime.vmHandler.EVT_APP_SET_FOREGROUND(EaHandler.MULTIMEDIA)		
		
	def stop(self):
		self.pause()
		runtime.vmHandler.EVT_APP_MIDLET_PAUSE('MULTIMEDIA')
		
		
	def sendPhonebookData(self, phoneNumber):
		from vmHandler import VmHandler
		runtime.vmHandler.EVT_APP_MESSAGE(VmHandler.MMSC, phoneNumber)
		
class WapBrowser(ExternalApplication):
	name = 'BROWSER'
	
	def __init__(self):
		ExternalApplication.__init__(self)

	def show(self):
		MD.mmiTrace('>>>>>>>>>>>> WapBrowser SHOW')
		os.system('fbtop 2')

	def pause(self):
		runtime.myannapp.send_mesg(config.EVT_APP_PAUSE)	
		runtime.SP_context.SP_stereoStopPlayback()
		self.browserKeyBlock()
		self.mmiKeyBlock()
		
	def resume(self, delayedShow=False):
		runtime.myannapp.send_mesg(config.EVT_APP_RESUME)
		runtime.SP_context.SP_stereoPlayback()
		self.browserKeyUnblock()
		self.mmiKeyUnblock()
		if delayedShow:
			return 'BROWSER'
		else:
			self.show()

	def start(self, sendMessage=False):
		if sendMessage:
			runtime.myannapp.send_mesg(config.EVT_APP_START)
			runtime.SP_context.SP_stereoPlayback()
		self.browserKeyUnblock()
		self.mmiKeyUnblock()
		self.show()
		
	def stop(self):
		MD.mmiTrace('WAPBROWSER::STOP')
		runtime.myannapp.send_mesg(config.EVT_APP_STOP)
		runtime.SP_context.SP_stereoStopPlayback()

	def sendPhonebookData(self, phoneNumber=None):
		itemList = []
		for item in phonebookList:
			itemList.append(item[0])

		sel_number = itemList[0]

		if phoneNumber:
			runtime.myannapp.send_mesg(config.EVT_APP_RESUME, 0, phoneNumber)
		else:
			runtime.myannapp.send_mesg(config.EVT_APP_RESUME, 1)

class Mmi(ExternalApplication):
	name = 'MMI'
	
	def __init__(self):
		ExternalApplication.__init__(self)

	def show(self):
		MD.mmiTrace('>>>>>>>>>>>> Mmi SHOW')
		os.system('fbtop 1')
		#import time
		#time.sleep(1)
		self.mmiKeyUnblock()

	def pause(self):
		self.mmiKeyBlock()

	def resume(self, delayedShow=False):
		#self.mmiKeyUnblock()
		if delayedShow:
			return 'MMI'
		else:
			self.show()

	def start(self, sendMessage=False):
		pass

class EaHandler:
	MMSC = 'MMSC'
	MULTIMEDIA = 'MULTIMEDIA'
	BROWSER = 'BROWSER'
	MMI = 'MMI'
	BANKING = 'BANKING'
	
	AUDIO_CALL = 1
	VIDEO_CALL = 2
	
	def __init__(self):
		self.mmsc = MmsClient()
		self.multimedia = MultimediaPlayer()
		self.browser = WapBrowser()
		self.mmi = Mmi()
		self.banking = BankingClient()
		
		self.foreground = self.mmi
		
		self.number = None
		self.callType = None

		self.source = None
		self.destination = None

		self.backup = None
		self.currentStage = None
		
		self.trafficHandler = None

		self.pathStack = []

		self.showingTraffic = False
		self.pauseTimer = None
		self.rcvPauseAckDo = None

	def setShowingTraffic(self, showingTraffic):
		self.showingTraffic = showingTraffic
		if self.showingTraffic:
			# VC02를 사용하는 교통정보 사용중인 경우에도 busy처리한다. 2008.06.23
			if runtime.dectCallManager.isSubcribedDect():
				from dectConfig import MessageCode
				runtime.dectCallManager.sendVideophoneStatusReportToDect(MessageCode.VP_STATUS.COMMON_NOTIFICATION)
				return
		else:
			# VC02를 사용하는 교통정보 사용중인 경우에도 busy처리한다. 2008.06.23
			if runtime.dectCallManager.isSubcribedDect():
				from dectConfig import MessageCode
				runtime.dectCallManager.sendVideophoneStatusReportToDect(MessageCode.VP_STATUS.IDLE)
				return

		
	def isShowingTraffic(self):
		return self.showingTraffic

	def clear(self):
		
		self.number = None
		self.callType = None

		if self.pathStack:
			self.source, self.destination, self.backup, self.currentStage = self.getPathInformation()
			self.foreground = self.destination
		else:
			self.foreground = self.mmi
			self.source = None
			self.destination = None
			self.backup = None
			self.currentStage = None
		#print 'ka....###### backup=', self.backup
		#print 'ka....###### currentStage=', self.currentStage

	def init(self):
		self.number = None
		self.callType = None
		self.foreground = None
		self.source = None
		self.destination = None
		self.backup = None
		self.currentStage = None
		self.pathStack = []
		self.showingTraffic = False
		runtime.vmHandler.playClear()
	
	def getApplication(self, application):
		if application == self.MMSC:
			return self.mmsc
		elif application == self.MULTIMEDIA:
			return self.multimedia
		elif application == self.BROWSER:
			return self.browser
		elif application == self.MMI:
			return self.mmi
		elif application == self.BANKING:
			return self.banking
	
	def setForeground(self, foreground):
		self.foreground = foreground

	def getForeground(self):
		return self.foreground
		
	def setSource(self, source):
		self.source = source 

	def getSource(self):
		return self.source

	def setDestination(self, destination):
		self.destination = destination

	def getDestination(self):
		return self.destination	
	
	def isAppInUse(self):
		#print '[MMI] isAppInuse: source:', self.source
		#print '[MMI] isAppInuse: destination:', self.destination
	
		if self.source == None or self.destination == None:
			return False
		else:
			return True
			
	def isDectInUse(self):
		from dectHandler import DectCallManager
		dectStatus = runtime.dectCallManager.getDectStatus()
		if dectStatus == DectCallManager.IDLE:
			return False
		else:
			return True
			
	def getBankInUse(self):
		if self.banking:
			return self.banking.bankInUse
		else:
			return False
			
	def openSpeaker(self):
		runtime.mmedia.unload()
		spkOffHook = runtime.SP_context.SPK_OffHook()
		if spkOffHook.next():
			spkOffHook.next()

	def setPath(self, source='MMI', destination='MMI'):
		self.source = self.getApplication(source)
		self.destination = self.getApplication(destination)

	def setPathInfomation(self, source='MMI', destination='MMI'):
		MD.mmiTrace('setPathInfomation:BEFORE:: ', self.pathStack)
		import copy
		#print 'ka.....runtime.manager.back=', runtime.manager.back
		backup = copy.copy(runtime.manager.back)
		#print 'ka.....runtime.manager.backup=', backup
		# 중복된 값은 삭제 해줘야 하는데,,,
		
		
		currentStage = runtime.manager.stage

		if self.source and self.destination:
			self.pathStack.append((self.source, self.destination, backup, currentStage))

		self.backup = backup
		self.currentStage = currentStage
		self.source = self.getApplication(source)
		self.destination = self.getApplication(destination)

		#print 'ka...........backup', self.backup
		#print 'ka...........currentStage', self.currentStage
		#print 'ka...........source', self.source
		#print 'ka...........destination', self.destination
		#print 'ka...........pathStack', self.pathStack

		MD.mmiTrace('self.backup:', self.backup)		
		MD.mmiTrace('setPathInfomation:AFTER:: ', self.pathStack)

	def getPathInformation(self):
		if self.pathStack:
			#print 'getPathInformation:: ', self.pathStack
			return self.pathStack.pop()


	def stageBackup(self):
		import copy
		self.backup = copy.copy(runtime.manager.back)
		self.currentStage = runtime.manager.stage
		
		print '------------------'
		backupLength = len(self.backup)
		print 'len = ', backupLength
		for i in range(backupLength):
			print 'name =', self.backup[i].get_name()
		print '------------------'

	def stageRestore(self):
		if self.backup:
			runtime.manager.remove_stage()
			#print 'ka.....stageRestore BEFORE :runtime.manager.back=', runtime.manager.back
			#print 'ka.....stageRestore BEFORE :runtime.manager.stage=', runtime.manager.stage
			
			backupLength = len(self.backup)
			#print '[MMI] len = ', backupLength
			for i in range(backupLength):
				stageName = self.backup[i].get_name()
				print '[MMI] stageRestore: name =', stageName
				if stageName == 'idle':
					pass
					#from model import IdleStage
					#runtime.manager.change_stage(IdleStage, True)	
				elif stageName == 'MenuStage':
					from model import MenuStage
					runtime.manager.stack_stage(MenuStage)
				elif stageName == 'myann':
					from myannapp import MyAnnStage
					runtime.manager.stack_stage(MyAnnStage(endCall=True))
				elif stageName == 'EaNotifyStage':
					from eaHandler import EaNotifyStage
					runtime.manager.stack_stage(EaNotifyStage)
			print 'ka.....stageRestore END :runtime.manager.back=', runtime.manager.back
			#self.backup = None

	def findStage(self, name):
		if not self.backup:
			return None
			
		for i in range(len(self.backup)):
			if self.backup[i].get_name() == name:
				print 'name = ', self.backup[i].get_name()
				return self.backup[i]		
				
	### Appliction 간 호출 ###############
	def startWAPfromBank(self):
		print '[MMI] goHomeFromBank:source', self.source
		if self.source:
			if self.getSource().getName() == EaHandler.MMI:
				# KA:[20081002] Base호 중 BANKING실행 
				#baseCallStatus, baseStatus, dectCallStatus, dectStatus = status.getCurrentCallStatus()
				#if baseStatus != SP_Context.IDLE:
				#	self.deactivateApplication() 
				#else:
				# KA:[20081002] Base호 중 BANKING실행  ==
				# goto Idle
				self.deactivateApplication(True) 
			elif self.getSource().getName() == EaHandler.BROWSER:
				# goto back
				self.gotoBrowser()

	def startCallWithoutNumber(self, source, key):
		# 실제 main 구동중인 EA (ex) browser 에서 media player 호출
		#print '[MMI] VM startCall', self.source
		#print '[MMI] VM startCall', self.destination
		if not self.source:
			return			
		currentName = runtime.eaHandler.getSource().getName()
		#print 'ka........self.currentName=', currentName
		if currentName == 'BROWSER':
			# source - browser / destination - multimeia / current name - browser
			os.system('fbtop 1')
			self.source.stop()
			self.source.mmiKeyUnblock()		
			#runtime.manager.back_stage('idle')
		# Call상태로 가기전 최종 EA
		elif source == 'BROWSER':
			os.system('fbtop 1')
			#self.deactivateApplication_browser()
			MD.mmiTrace('********** deactivateApplication_browser 2')
			self.destination.stop()
			self.source.mmiKeyUnblock()		
		elif source == 'MULTIMEDIA':
			self.readyMessageMMSC()
			self.activateApplication(source)
		else:
			self.activateApplication(source)
		self.init()


		baseCallStatus, baseStatus, dectCallStatus, dectStatus = status.getCurrentCallStatus()
		from dectHandler import DectCallManager
		if dectStatus != DectCallManager.IDLE:
			stage = NotifyStage(_('Dect in use.'), uiconfig.setting_voip_icon)
			runtime.manager.change_stage(stage, True)
			return			

		if key == config.OffHook:
			runtime.manager.handle_offhook()
		elif key == config.Green or key == config.Video:
			runtime.manager.handle_green()
		elif key == config.key_link_down:
			print 'call without number: link down'
			
	def startAudioCall(self, source, number):
		self.activateApplication(source)
		self.init()

		baseCallStatus, baseStatus, dectCallStatus, dectStatus = status.getCurrentCallStatus()
		from dectHandler import DectCallManager
		if dectStatus != DectCallManager.IDLE:
			stage = NotifyStage(_('Dect in use.'), uiconfig.setting_voip_icon)
			runtime.manager.change_stage(stage, True)
			return
		self.openSpeaker()
		runtime.SP_context.setBaseStatus(SP_Context.DIALING)
		runtime.manager.start_call(number) 
		return


	def startVideoCall(self, source, number):
		self.activateApplication(source)
		self.init()

		baseCallStatus, baseStatus, dectCallStatus, dectStatus = status.getCurrentCallStatus()
		from dectHandler import DectCallManager
		if dectStatus != DectCallManager.IDLE:
			stage = NotifyStage(_('Dect in use.'), uiconfig.setting_voip_icon)
			runtime.manager.change_stage(stage, True)
			return
		self.openSpeaker()
		runtime.SP_context.setBaseStatus(SP_Context.DIALING)
		runtime.manager.start_call(number, video_call=True) 
		return
		
	def startWapCall(self, number, video_call=False):
		runtime.manager.stack_stage(EaNotifyStage('VideoCall : In Use By BROWSER'))		
		self.activateApplication('BROWSER')
		
		if status.get_register_mode() == status.NotRegistered:
			def cb():
				#self.deactivateApplication_browser()
				from model import IdleStage
				runtime.manager.change_stage_org(IdleStage, True)
			stage = NotifyStage(_('You should register first'), uiconfig.profile_icon, cb)
			runtime.manager.stack_stage(stage)
			#status.dial_number = ''
			return

		baseCallStatus, baseStatus, dectCallStatus, dectStatus = status.getCurrentCallStatus()
		from dectHandler import DectCallManager
		if dectStatus != DectCallManager.IDLE:
			def cb():
				#self.deactivateApplication_browser()
				from model import IdleStage
				runtime.manager.change_stage_org(IdleStage, True)
			stage = NotifyStage(_('Dect in use.'), uiconfig.setting_voip_icon, cb)
			runtime.manager.change_stage(stage)
			return

		self.openSpeaker()		

		runtime.SP_context.setBaseStatus(SP_Context.DIALING)
		runtime.manager.start_call(number, video_call) 

	def endCall(self, missed=False):
		if self.isAppInUse():
			print '[MMI] endCall: source=', self.source
			print '[MMI] endCall: destination=', self.destination

			# KA:[20081002] Base호 중 BANKING실행 
			# BANKING의 경우에는 호중에 BANKING 을 띄우고 Idle로 돌아간 경우 no action
			#if self.destination:
			#	if self.destination.getName() == 'BANKING':
			#		return True
			# KA:[20081002] Base호 중 BANKING실행 ==
			
			if self.destination:
				if self.destination.getName() == 'MMI':
					self.destination.pause()
				else:
					self.destination.resume()
			if self.source:
				if self.source.getName() == 'MMI':
					self.source.pause()
				else:
					self.source.resume()		
			
			self.clear()
			self.stageRestore()			
			#print '[MMI] endCall2: source=', self.source
			#print '[MMI] endCall2: destination=', self.destination			
			

	def openPhonebook(self, source='MMI', destination='MMI'):
		if source == 'BROWSER':
			runtime.manager.stack_stage(EaNotifyStage('VideoCall : In Use By BROWSER'))
		elif source == 'MULTIMEDIA':
			runtime.manager.stack_stage(EaNotifyStage('VideoCall : In Use By MULTIMEDIA'))
		elif source == 'MMSC':
			runtime.manager.stack_stage(EaNotifyStage('VideoCall : In Use By MMSC'))

		self.activateApplication(source, destination)

		from phonedb import phonedb
		if phonedb.is_empty():
			import uiconfig
			def back_cb():
				runtime.manager.back_stage()
				runtime.eaHandler.closePhonebook()
			runtime.manager.stack_stage(NotifyStage(_('Phonebook empty'), uiconfig.baloon_phonebook_icon, back_cb))
			return

		from basemodel import SearchStage
		runtime.manager.stack_stage(SearchStage(left=_('OK'), vm_flag=True))

	def openGroupbook(self, source='MMI', destination='MMI'):
		if source == 'BROWSER':
			runtime.manager.stack_stage(EaNotifyStage('VideoCall : In Use By BROWSER'))
		elif source == 'MULTIMEDIA':
			runtime.manager.stack_stage(EaNotifyStage('VideoCall : In Use By MULTIMEDIA'))
		elif source == 'MMSC':
			runtime.manager.stack_stage(EaNotifyStage('VideoCall : In Use By MMSC'))

		self.activateApplication(source, destination)

		from phonebook import GroupStage
		runtime.manager.stack_stage(GroupStage(vm_flag = True))

	def openAddPhonebook(self, source='MMI', destination='MMI', data=''):
		if source == 'BROWSER':
			runtime.manager.stack_stage(EaNotifyStage('VideoCall : In Use By BROWSER'))
		elif source == 'MULTIMEDIA':
			runtime.manager.stack_stage(EaNotifyStage('VideoCall : In Use By MULTIMEDIA'))
		elif source == 'MMSC':
			runtime.manager.stack_stage(EaNotifyStage('VideoCall : In Use By MMSC'))

		self.activateApplication(source, destination)

		from phonedb import phonedb
		if phonedb.count() >= config.phone_db_size:
			import uiconfig
			def back_cb():
				runtime.manager.back_stage()
				runtime.eaHandler.closePhonebook()
			runtime.manager.stack_stage(NotifyStage(_('Memory full'), uiconfig.baloon_phonebook_icon, back_cb))
			return		

		from phonebook import AddPhoneBookStage
		runtime.manager.stack_stage(AddPhoneBookStage(number = data, vm_flag = True))	

	def closePhonebook(self):
		self.deactivateMMI()
		
	def sendPhonebookData(self, data):
		#self.source.sendPhonebookData(data)
		MmsClient().sendPhonebookData(data)

####################
	def startBANKING(self, source='MMI'):
		runtime.manager.stack_stage(EaNotifyStage('VideoCall : In Use By MMSC'))
		runtime.eaHandler.activateApplication(source, destination=EaHandler.BANKING)		
		runtime.vmHandler.EVT_APP_SET_FOREGROUND(EaHandler.BANKING)

	def startMMSC(self):
		runtime.manager.stack_stage(EaNotifyStage('VideoCall : In Use By MMSC'))
		runtime.eaHandler.activateApplication(destination=EaHandler.MMSC)
		runtime.vmHandler.EVT_APP_SET_FOREGROUND(EaHandler.MMSC)
		# temporay 2008.06.04
		runtime.eaHandler.startAsInitialMode()

	def startMediaPlayer(self):
		runtime.manager.stack_stage(EaNotifyStage('VideoCall : In Use By MULTIMEDIA'))
		message = 'goto:mediaPlayer'
		runtime.vmHandler.EVT_APP_MESSAGE(VmHandler.MULTIMEDIA, message)
		self.activateApplication(destination=EaHandler.MULTIMEDIA)
		runtime.vmHandler.EVT_APP_SET_FOREGROUND(EaHandler.MULTIMEDIA)
	
	def startDownloadContents(self):
		runtime.manager.stack_stage(EaNotifyStage('VideoCall : In Use By MULTIMEDIA'))
		message = 'goto:download'
		runtime.vmHandler.EVT_APP_MESSAGE(VmHandler.MULTIMEDIA, message)
		self.activateApplication(destination=EaHandler.MULTIMEDIA)
		runtime.vmHandler.EVT_APP_SET_FOREGROUND(EaHandler.MULTIMEDIA)
####################

	def readNewMessage(self, source='MMI', destination='MMSC'):
		self.activateApplication(source, destination)
		runtime.vmHandler.EVT_APP_MESSAGE(VmHandler.MMSC, 'goto:inbox')

	###### APPLICATION ACTIVE/DEACTIVE
	def activateApplication(self, source='MMI', destination='MMI'):
		MD.mmiTrace('********* activateApplication START')
		self.setPathInfomation(source, destination)
		#print '[MMI] activateApplication: self.source=', self.source
		#print '[MMI] activateApplication: destination=', self.destination
		self.source.pause()
		self.setForeground(self.destination)
		self.destination.resume()

	
	def activateApplicationByCall(self, source='MMI', destination='MMI'):
		MD.mmiTrace('********* activateApplication START by Call')
		self.setPathInfomation(source, 'MMI')
		#print '[MMI] activateApplicationByCall: self.source=', self.source
		#print '[MMI] activateApplicationByCall: destination=', self.destination
		self.source.pause()
		self.setForeground(self.destination)
		#self.destination.resume()
		#if runtime.vmHandler.vmAliveTimer:
		#	# 이미 red key를 눌러서 Idle로 돌아가는 중~
		#	print 'ka.....### running~ Red Key Timer'
		#	self.rcvPauseAck()
		#	return		
		self.waitPauseAck()

	def waitPauseAck(self):
		import utils
		print 'ka....############ waitPauseAck----------'
		self.pauseTimer = utils.Timer(20 * 1000, runtime.vmHandler.reRunVmHandler)

	def rcvPauseAck(self, callError=False):
		if not self.pauseTimer:
			return
		print 'ka....############ waitPauseTimer clear----------'
		self.pauseTimer = None
		self.destination = self.getApplication('MMI')
		self.destination.resume()
		if self.rcvPauseAckDo:
			runtime.manager.stack_stage(self.rcvPauseAckDo)
			self.rcvPauseAckDo = None
			return
		if not callError:		
			runtime.vdciapp.vm_server_incoming()
		# callError - Incoming 와서 pausewait 하는 중에 E|C가 올라오는 경우


		#wait_stop_timer

	def rcvPauseAckDoFunction(self, data):
		self.rcvPauseAckDo = data
		
	def activateApplication_browser(self, source='MMI', destination='MMI'):
		MD.mmiTrace('********** activateApplication_browser START')
		self.setPathInfomation(source=source, destination=destination)
		self.source.pause()
		self.setForeground(self.destination)
		self.destination.start()

	def gotoBrowser(self):
		#print '[MMI] gotoBrowser: source=', self.source #---- browser 여야 한다. 
		#print '[MMI] gotoBrowser: destination=', self.destination
		if self.destination:
			#self.readyMessageMMSC()
			self.destination.pause()	
		if self.source:
			self.source.resume()
		runtime.manager.back_stage('myann') # EaNotify에서 myannapp로 back()
		self.clear()

	def gotoMMI(self, gotoIdle=False):
		print '[MMI] gotoMMI: destination=', self.destination

		# MMSC -> MMI 인 경우에만 속도 개선을 위해 MMI화면을 먼저 불러준다.
		if self.destination:
			if self.destination.getName() == 'MMSC':
				self.source.resume()
				self.destination.pause()

				self.init()
				if not runtime.manager.find_stage('MenuStage') or gotoIdle:
					if runtime.manager.find_stage('idle'):
						runtime.manager.back_stage('idle')
					else:
						from model import IdleStage
						runtime.manager.change_stage_org(IdleStage, True)
				else:		
					runtime.manager.back_stage('MenuStage')
				
				return

			# KA:[20081002] Base호 중 BANKING실행 
			#if self.destination.getName() == 'BANKING':
			#	self.source.resume()
			#	self.destination.pause()
			#	self.init()
#
#				if runtime.manager.find_stage('AudioCallConnected') or \
#					runtime.manager.stage.get_name() == 'AudioCallConnected':
#					runtime.manager.back_stage('AudioCallConnected')
#				elif not runtime.manager.find_stage('MenuStage') or gotoIdle:
#					if runtime.manager.find_stage('idle'):
#						runtime.manager.back_stage('idle')
#					else:
#						from model import IdleStage
#						runtime.manager.change_stage_org(IdleStage, True)
#				else:		
#					runtime.manager.back_stage('MenuStage')
#				return True
			# KA:[20081002] Base호 중 BANKING실행 
		
		if self.destination:
			self.destination.pause()	
		if self.source:
			self.source.resume()			
		self.init()

		if not runtime.manager.find_stage('MenuStage') or gotoIdle:
			if runtime.manager.find_stage('idle'):
				runtime.manager.back_stage('idle')
			else:
				from model import IdleStage
				runtime.manager.change_stage_org(IdleStage, True)
		else:		
			runtime.manager.back_stage('MenuStage')
		
	def deactivateMMI(self):
		#print '[MMI] deactivateMMI: source=', self.source 
		#print '[MMI] deactivateMMI: destination=', self.destination #---- MMI 여야 한다. 
		if self.destination:
			if self.destination.getName() == 'MMI':
				self.destination.pause()
			else:
				self.destination.resume()
		if self.source:
			if self.source.getName() == 'MMI':
				self.source.pause()
			else:
				self.source.resume()
		self.clear()	
		
	def deactivateApplication(self, gotoIdle=False):
		MD.mmiTrace('********** deactivateApplication START')
		print '[MMI] deactivateApplication: source=', self.source
		print '[MMI] deactivateApplication: destination=', self.destination

		if self.source:
			if self.source.getName() == 'MMI':
				self.gotoMMI(gotoIdle)
				return		

		#for red key - end all
		if gotoIdle and self.source:
			if self.getSource().getName() == 'BROWSER':		
				if self.destination:
					self.destination.pause()
				if self.source:
					self.source.stop()
				self.source.mmiKeyUnblock()
				self.init()
				os.system('fbtop 1')
				from model import IdleStage
				runtime.manager.change_stage_org(IdleStage, True)			
				return

		# Banking에서 이전 키 누르는 경우
		if self.source:
			if self.source.getName() == 'BROWSER':
				self.startWAPfromBank()
				return				

			
		'''
		if gotoIdle:
			if self.source:
				if self.getSource().getName() == 'BROWSER':
					if self.destination:
						self.destination.pause()
					if self.source:
						self.source.stop()
					self.source.mmiKeyUnblock()
					self.init()
					os.system('fbtop 1')
					from model import IdleStage
					runtime.manager.change_stage(IdleStage(oninitFlag=False), True)			
					return
			if self.destination:
				if self.destination.getName() == 'BROWSER':
					if self.destination:
						self.destination.stop()
					if self.source:
						self.source.pause()
					self.source.mmiKeyUnblock()
					self.init()
					os.system('fbtop 1')
					from model import IdleStage
					runtime.manager.change_stage(IdleStage(oninitFlag=False), True)			
					return
		'''

#		if self.destination:
#			self.destination.pause()
#		if self.source:
#			delayedShowName = self.source.resume(delayedShow=True)

		if gotoIdle:
			MD.mmiTrace('******** GOTO IDLE')
			
			#pathInfoLength = len(self.pathStack)
			#for index in range(pathInfoLength):
			#	source, destination, backup, currentStage = self.pathStack.pop()
			#	print '[MMI] SEND STOP ==============############'
			#	destination.stop()
			# MMSC가 불려진 상태에서 Media player 동작 후  RED키로 종료시 대기화면 MSG를 날리면 초기 진입시 Media 화면 대신 대기 화면을 보도록
#			if self.destination:
#				if self.destination.getName() == 'MMSC':	
#					self.readyMessageMMSC()

			if self.destination:
				if self.destination.getName() == 'MMI':
					#self.destination.resume(delayedShow=True)
					self.destination.resume()
				else:
					if self.destination.getName() == 'MMSC':	
						self.readyMessageMMSC()
					self.destination.pause()
			if self.source:
				if self.source.getName() == 'MMI':
					#self.source.resume(delayedShow=True)
					self.source.resume()
				else:
					if self.source.getName() == 'MMSC':	
						self.readyMessageMMSC()
					self.source.pause()					
					
			from model import IdleStage
			#self.clear()
			self.init()
			# for test
			#runtime.manager.change_stage_org(IdleStage(oninitFlag=False), True)
			runtime.manager.change_stage(IdleStage, True)
			#delayedShowName = 'MMI'
			#runtime.manager.save_idle_stage()
			#runtime.manager.back_stage()
			
			
		else:
			if self.destination:
				if self.destination.getName() == 'MMI':
					self.destination.resume()
				else:
					self.destination.pause()
			if self.source:
				if self.source.getName() == 'MMI':
					self.source.resume()
				else:
					self.source.pause()
					
			MD.mmiTrace('******** GOTO BACK')
			#if self.source == self.MMI:
			#	self.init()
			#else:
			#	self.source = self.destination
			#	self.destination = None

			if self.destination:
				if self.destination.getName() == 'MMI':
					if self.source:
						if self.source.getName() == 'MMI':
							print 'ka....### init'
							self.init()

			#self.clear()
			self.init()
			
			if runtime.manager.find_stage('MenuStage'):
				runtime.manager.back_stage('MenuStage')
			else:
				if runtime.manager.find_stage('idle'):
					runtime.manager.back_stage('idle')
				else:
					from model import IdleStage
					runtime.manager.change_stage_org(IdleStage, True)


		#if delayedShowName:
		#	def delayedShow():
		#		self.showNow(delayedShowName)
		#		self.delayedShowTimer = None
		#		return False
		#	import utils
		#	self.delayedShowTimer = utils.Timer(500, delayedShow)

	def showNow(self, name):
		MD.mmiTrace('********** DELAYED showNow START')
		if name == self.MMI:
			self.mmi.show()
		elif name == self.BROWSER:
			self.browser.show()
		elif name == self.MMSC:
			self.mmsc.show()
		elif name == self.MULTIMEDIA:
			self.multimedia.show()	
	
			
	def deactivateApplication_browser(self):
		MD.mmiTrace('********** deactivateApplication_browser START')
		print '[MMI] de browser: source:', self.source
		print '[MMI] de browser: destination:', self.destination
		if self.destination and self.destination.getName() == 'BROWSER':
			self.destination.stop()
			self.destination.mmiKeyUnblock()
		elif self.source and self.source.getName() == 'BROWSER':
			self.source.stop()			
			self.source.mmiKeyUnblock()		
		#self.clear()
		self.init()
		#runtime.manager.back_stage('idle')
		
		from mmiSoundPath import SP_Context, SP_State
		from dectHandler import DectCallManager
		baseCallStatus, baseStatus, dectCallStatus, dectStatus = status.getCurrentCallStatus()
		#print 'ka...########## baseCallStatus, baseStatus, dectCallStatus, dectStatus =', baseCallStatus, baseStatus, dectCallStatus, dectStatus 
		if status.video_mode != status.VideoIdle: # base Idle상태인 경우만 / 덱트가 호 중이어도 Idle
			if baseStatus != SP_Context.IDLE:
				return
		
		from model import IdleStage
		runtime.manager.change_stage_org(IdleStage, True)			

	def sendMissedCallAlarm(self, callType, smsReceivingNumber, callerName, callerNumber, keep):
		import time
		year, mon, day, hour, min, sec = time.localtime(ntptime.ntime())[:6]
		date = "%04d%02d%02d%02d%02d%02d" % (year, mon, day, hour, min, sec)
		# callerName을 10byte로 맞춰보내준다. 
		callerName = unicode(callerName, 'utf-8').encode('euc-kr')
		if len(callerName) > 10:
			try:
				l = 8
				tmp = unicode(callerName[:8], 'euc-kr').encode('utf-8')
			except:
				l = 7	#tmp = unicode(callerName[:7], 'euc-kr').encode('utf-8')			
			callerName = callerName[:l] + '..'			
		
		# 우이씨~ 메시지 번호도 순서를 맞춰달라니;;
		number = smsReceivingNumber.split(';')
		numberList = []
		for i in range(3):
			if len(number[i]) != 0:
				numberList.append(number[i])
		for i in range(3):
			if len(numberList) < 3:
				numberList.append('')
		smsReceivingNumber = ';'.join(numberList)
		
		message = 'missed://' + '%d;%s;%s;%s;%s;%d' % (callType, smsReceivingNumber, callerName, callerNumber, date, keep)
		runtime.vmHandler.EVT_APP_MESSAGE(VmHandler.MMSC, message)

	
	###### send MMS
	def sendMmsMessageInMmi(self, number, name):
		destination = self.MMSC
		runtime.manager.stack_stage(EaNotifyStage('VideoCall : In Use By MULTIMEDIA'))

		self.activateApplication('MMI', destination)
		name = unicode(name, 'utf-8').encode('euc-kr')
		
		message = 'mms://' + number + ';' + name
		runtime.vmHandler.EVT_APP_MESSAGE(VmHandler.MMSC, message)
		runtime.vmHandler.EVT_APP_SET_FOREGROUND(EaHandler.MMSC)
	
	###### TRAFFIC INFORMATION
	def startTraffic(self, cid, x, y, screenWidth, screenHeight):
		self.setShowingTraffic(True)
		from trafficHandler import TrafficHandler
		self.trafficHandler = TrafficHandler(cid, x, y, screenWidth, screenHeight)		

		# 처음 startTraffic()호출시: 한번 정리후에 시작(powerOff나 비정상 종료를 후에)
		self.stopTraffic()
		self.trafficHandler.B2T_GetImageStream()
		
	def stopTraffic(self):
		self.setShowingTraffic(False)
		if not self.trafficHandler:
			MD.mmiException('SOCKET ERROR in TRAFFIC INFO.')
			return
		self.trafficHandler.B2T_StopImageStream()

	def startAsInitialMode(self):
		message = 'goto:initial'
		runtime.vmHandler.EVT_APP_MESSAGE(VmHandler.MMSC, message)

	def stopDownloadContents(self):
		self.deactivateApplication()
		
	###### Media Player - from my ann
	def playMediaFile(self, source, fileName):
		destination = self.MULTIMEDIA
		runtime.manager.stack_stage(EaNotifyStage('VideoCall : In Use By MULTIMEDIA'))
		self.activateApplication(source, destination)
		message = 'file://' + fileName + '?from=' + source
		runtime.vmHandler.EVT_APP_MESSAGE(VmHandler.MULTIMEDIA, message)
		runtime.vmHandler.EVT_APP_SET_FOREGROUND(EaHandler.MULTIMEDIA)

	def updateCookiesFromWap(self, sip=True):
		if sip:
			path = config.SIP_COOKIE_FILE
		else:
			path = config.WAP_COOKIE_FILE

		# file check
		if os.path.exists(path) == False:
			return 	
		#runtime.vmHandler.setTerminalInformation()
		runtime.myannapp.update_browser_cookie(path)
		runtime.vmHandler.VM_COOKIE_UPDATE_REQ(path)
		# for syncML
		command = 'cp %s %s'%(path, config.SYNC_COOKIE_FILE)
		os.system(command)
		
	def readyMessageMMSC(self):
		#self.activateApplication(source, destination)
		runtime.vmHandler.EVT_APP_MESSAGE(VmHandler.MMSC, 'goto:ready')

		
		
from basemodel import Stage, NotifyStage
import baseui
import uiconfig

class EaNotifyStage(Stage):
	name = 'EaNotifyStage'
	domonitor_forbidden = True
	
	def __init__(self, message='', isred=True):
		icon = uiconfig.baloon_setting_voip_icon
		status.supervision_not_allowed = 1
		self.isred = isred
		# for wording
		message = _('Please wait...')
		self.ui = baseui.NotifyUI(message, icon)
		
	def show(self):
		status.supervision_not_allowed = 1
		Stage.show(self)

	def hide(self):
		self.destroy_tag = None
		Stage.hide(self)

	def handle_key(self, key):
		if key == config.Red:
			runtime.manager.back_stage()
		return True

	def destroy(self):
		status.supervision_not_allowed = 0
		Stage.destroy(self)
		self.destroy_tag = 0

'''		
class DectInUseNotifyStage(NotifyStage):
	def __init__(self, message,cb=None):
		icon = uiconfig.baloon_setting_voip_icon
		NotifyStage.__init__(self, message, icon, cb)
			
	def destroy(self):
		MD.mmiTrace('DectInUseNotifyStage:destroy() : DECT IN USE NOTI!!! ==> change SHOW!')
		self.changeShow()
'''