from MetaEditAPI_services import *
import sys

class Transition:
  def __init__(self, name='Transition'):
    self.name = name

  def __str__(self):
    return self.name

  def execute(self, listNodes, readLine):

    """
        Initializes access to the API
    """
    service = MetaEditAPILocator()
    kw = { 'tracefile' : sys.stdout }
    port = service.getMetaEditAPIPortType(**kw)

    graphType = ns0.METype_Def("FSA")
    graphType._name = "FiniteStateAutomata"

    agir = allGoodInstancesRequest()
    agir._receiver = graphType
    graph = port.allGoodInstances(agir)

    tempAny = ns0.METype_Def("ta")
    tempAny._name = ""
    result = []
    result2 = None
    isCurrentPresent = False

    """
        Retrieves all relationships from the graph
    """
    rsr = relationshipSetRequest()
    rsr._receiver = graph._result[0]
    rfor_result = port.relationshipSet(rsr)

    for i in range(0, len(rfor_result._result)):
        """
            Searches for the realtion which has the value passed in readLine
        """
        vAtRequest = valueAtRequest()
        vAtRequest._receiver = rfor_result._result[i]
        vAtRequest._valueAt = 1
        vAtResponse = port.valueAt(vAtRequest)

        """
            If there is a match, then append it
        """
        if vAtResponse._result._meValue == ("'" + readLine[0:len(readLine)-1] + "'")  :
            result.append(rfor_result._result[i])

    if result != None :
        """
            Searches for the transition that is actually related to the current state
            then grabs the next state
        """
        for j in range(0, len(result)):
            ofrr = objsForRelRequest()
            ofrr._receiver = graph._result[0]
            ofrr._objsForRel = result[j]
            ofrr._ofClass = tempAny
            ofrr_result = port.objsForRel(ofrr)

            if len(ofrr_result._result) == 2 :
                for i in range(0, len(ofrr_result._result)):
                    print listNodes['Current']
                    if ofrr_result._result[i]._objectID == listNodes['Current']._objectID :
                        isCurrentPresent = True
                    else:
                        result2 = ofrr_result._result[i]

            if isCurrentPresent == True :
                break

    """
        Animates the current state if it has changed
    """
    if isCurrentPresent == True and len(ofrr_result._result) == 2 and result2 != None:
        listNodes['Current'] = result2
        animate = animateRequest()
        animate._receiver = graph._result[0]
        animate._animate = listNodes['Current']
        animateResult = port.animate(animate)

    print "Animate State %s" % listNodes['Current']._objectID


    return listNodes
