#!/usr/bin/env python
# -*- Python -*-

import sys
import time
# import os
import subprocess

#
# set up user environment
#  RtmToolsDir, MyRtcDir, etc.
#
from set_env import *
#
# import user tools
#
save_path = sys.path[:]
sys.path.append(Rh2LibDir)
from rtc_handle import *
sys.path.append(Rh2LibDir+'/tools/geo')
from geo import *

#
# import stub files
# 
sys.path.append(Rh2IdlDir)
import _GlobalIDL
sys.path = save_path

def assign_variables(env) :
  # rtc
  global ARMarkerDetectSimple, CaptureTimedCameraImage
  ARMarkerDetectSimple = env.name_space[Rh2ARNS].rtc_handles['ARMarkerDetectSimple0.rtc']
  CaptureTimedCameraImage = env.name_space[Rh2ARNS].rtc_handles['CaptureTimedCameraImage0.rtc']
  ARMarkerDetectSimple.outports['MarkerPose'].open()
  ARMarkerDetectSimple.outports['MarkerPoseAll'].open()
  #configuration
  ARMarkerDetectSimple.conf_ref.activate_configuration_set('Logicool')
  # data & class

def make_connectors(env):
  env.con_list=[]
#0
  con = IOConnector([CaptureTimedCameraImage.outports['Image'],ARMarkerDetectSimple.inports['Image']])
  env.con_list.append(con)

#
# connection control
#
def disconnect_all(env) :
  for con in env.con_list :
    con.disconnect()
def connect_list(env,ll) :
  for i in ll :
    env.con_list[i].connect()
def disconnect_list(env,ll) :
  for i in ll :
    env.con_list[i].disconnect()

def activate_seq(a_seq) :
  for tmp in a_seq :
    if isinstance(tmp,RtcHandle) :
      tmp.activate()
    elif isinstance(tmp, int) :
      time.sleep(tmp)
    elif isinstance(tmp, float) :
      time.sleep(tmp)
    else :
      eval(tmp)

def deactivate_all() :
#  slider.deactivate()
  ARMarkerDetectSimple.deactivate()
  CaptureTimedCameraImage.deactivate()

def end(env):
  #disconnect_all(env)
  deactivate_all()
  ARMarkerDetectSimple.outports['MarkerPose'].close()
  ARMarkerDetectSimple.outports['MarkerPoseAll'].close()


#
# AR RTC ready
##
def start_ARrecog(env) :
  #connect_list(env,[0])
  activate_seq([ARMarkerDetectSimple,CaptureTimedCameraImage])

def stop_ARrecog(env) :
  deactivate_all()
  #disconnect_all(env)

def get_specified_data() :
  global data
  try:
    data = ARMarkerDetectSimple.outports['MarkerPose'].read().data
    print"Marker was detected."
    return 0
  except AttributeError:
    return 1

def get_all_data() :
  global all_data
  try:
    all_data = ARMarkerDetectSimple.outports['MarkerPoseAll'].read().data
    print"Marker was detected."
    return 0
  except AttributeError:
    return 1

#
# create env
#
env = RtmEnv(sys.argv,[Rh2ARNS])
#run_components()
#raw_input("are you sure that each rtc needed is running?")
for ns in env.name_space :
  env.name_space[ns].list_obj()
assign_variables(env)


