"""
<Program Name>
  z_test_sends_final_ack.repy

<Started>
  February 7, 2009

<Author>
  Michael Moshofsky

<Purpose>
  To make sure the Ack is sent after a SYNACK is recieved
  while the Connection class is trying to connect.

  Raises exception when a Ack is not sent after a SYNAck
  is received.

"""



include tcp.repy


def listenForSYNAndACK(remoteIP, remoteport, message, commhandle):
  packet = unpack(message)
  if(packet.is_syn()):
    packetSYNAck = TcpPacket(mycontext['SECOND_PORT'], mycontext['PORT'], 1, mod_add(packet.seq_num, 1), "SYNACK", WINDOW_SIZE, "synacking...").pack()
    sendmess(remoteIP, mycontext['PORT'], packetSYNAck, IP, mycontext['SECOND_PORT'])
  elif(packet.is_ack()):
    mycontext['receivedACK'] = True



if callfunc == 'initialize':
  IP = '127.0.0.1' #  getmyip()
  mycontext['PORT'] = 12345
  mycontext['SECOND_PORT'] = 12346

  mycontext['receivedACK'] = False

  socket = Connection()
  socket.bind(IP, mycontext['PORT'])

  recvmess(IP, mycontext['SECOND_PORT'], listenForSYNAndACK)

  socket.connect(IP, mycontext['SECOND_PORT'])

  sleep(DEFAULT_TIMEOUT)

  if (mycontext['receivedACK'] != True):
      raise Exception("Ack was not sent after a SYNAck was recieved.")

#  socket.disconnect()
  exitall()


