#!/usr/bin/env python
# Echo server program
import select
import socket
import sys

HOST = 'localhost'        # Symbolic name meaning all available interfaces
PORT = 50018              # Arbitrary non-privileged port
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST, PORT))
server.listen(5)
input = [server,sys.stdin]
numbidders = 2
bidderports = []

nummoves = 3
j = 0
while(j < nummoves):
  print("move j is: ", j)
  bidderports = []
  bids = []
  while(numbidders > len(bidderports)):
   inputready,outputready,exceptready = select.select(input,[],[])
   for s in inputready:
    if s == server:
	print("In server case")
	client, address = server.accept()
	input.append(client)
    if((s != server) & (s!=sys.stdin)):
      data = s.recv(1024)
      if not data: 
	print("Have not received data from", str(s))
      indata = data.split(" ")
      print(' '.join(indata))
      if(indata[0] in bidderports):
      	s.send("Not ready " + indata[0] + " to tell you about move " + str(j) )
      else:
         s.send("Thank you, " + indata[0] +  " I have received your bid of " + indata[1])
         bids.append(int(indata[1]))
         bidderports.append(indata[0])
         print("number of bids received is: ", len(bidderports))
  # Now have all the bids
  bestbid = max(bids)
  print("Here are the bids ")
  print(bids)
  print("Best bid for step ", j, " is ", bestbid)
  print("Here are the ports ") 
  print(bidderports)

  # Now receive requests for results
  deletedindexes = [] # record which indexes are gone
  while(numbidders > len(deletedindexes)):
   inputready,outputready,exceptready = select.select(input,[],[])
   for s in inputready:
    if((s != server) & (s!=sys.stdin)):
      data = s.recv(1024)
      if not data: 
	print("Have not received data from", str(s))
      indata = data.split(" ")
      print(' '.join(indata))
      myindex = bidderports.index(indata[0])
      if(myindex not in deletedindexes):
	   deletedindexes.append(myindex)
           if(bids[myindex] == bestbid):
    		s.send(bidderports[myindex] + ' you have bought this item')
           else:
    		s.send(bidderports[myindex] + ' someone else has bought this item for ' + str(bestbid))
      else:
         s.send("Not ready for next round yet " + indata[0])
  j+=1
