    # -*- coding: utf-8 -*-
"""
Created on Wed Sep 12 19:36:31 2018

@author: Dhruv
"""

# first of all import the socket library 
import socket   
#import sys     
import time         
import _thread 
import random  

# next create a socket object 
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)          
print("Socket successfully created")
  
# reserve a port on your computer in our 
# case it is 12345 but it can be anything 
port = 3236                 
  
# Next bind to the port 
# we have not typed any ip in the ip field 
# instead we have inputted an empty string 
# this makes the server listen to requests  
# coming from other computers on the network 
s.bind(('127.0.0.1', port))         
print("socket binded to %s" %(port)) 
  
# put the socket into listening mode 
s.listen(5)      
print("socket is listening")            
   # Establish connection with client. 
# thread 1 will generate random numbers within 3 seconds and thread 2 will delete the first element 
    #  from the storage which were generated by thread 1
Services=[]
Services_Port=[]
def get_random(name,S_time):
        
        count=0
        #start=time.time()
        # y=random.randint(1,100)
        #print(x)
        while count<15:
            
            time.sleep(S_time)
            y=random.randint(1,100)
            #x.append(y)
           # x=random.randint(1,100)
            m=port+y
            print("%s generated: %s on port %s "%(name,y,m))
            Services.append(y)
            Services_Port.append(m)

            count+=1
            
def remove_it(t_name,E_time):
        count=0
                
        while count<15:
#            if len(x)==2 and  len(x)==1:
#                pass
#            elif len(x)>3:           
                time.sleep(E_time)
                print("-----%s removed: %s from port %s"%(t_name,Services[0],Services_Port[0]))
                print("------")
                Services.pop(0)
                Services_Port.pop(0)
                print("Services: %s  and Port:%s "%(Services,Services_Port))
                            
    
try:
        
        _thread.start_new_thread(get_random,('thread_1',3,))
        _thread.start_new_thread(remove_it,('thread_2',6, ))
    
    
except:
        print('Error: Something went wrong!')

 
m=True 
# a forever loop until we interrupt it or  
# an error occurs 

client, addr = s.accept() 
#   # Establish connection with client. 
#   client, addr = s.accept()      
print('Got connection from', addr)
  
   # send a thank you message to the client. 
  #  time.sleep(2)

while m:   
    temp=client.recv(64)


#temp = int(data)
#modifiedMessage, serverAddress = s.recvfrom(temp.decode('utf-8'))
    #sub = re.findall('\[(.*?)\]', str(temp))
    temp = str(temp)
    temp = temp[2:]
    temp = temp[:-1]
    temp = int(temp)
#temp = data.decode()
    print(temp)
    print('--- -- - -- - - -- - ')
    #   data=data[::-1]
   
    # creating a 2 thread for random generator
    
    # thread 1 will generate random numbers within 3 seconds and thread 2 will delete the first element 
    #  from the storage which were generated by thread 1
    
   
#now we have to generate a random number and check if it is available or not ?????
# Now we import the thread program that concurrent with the service requester


   # x=[10,20,30,40,50,60,70]
#
    if temp in Services: 
        # displaying the client number
            print('from connected user: '+str(temp))
            i=("Yes, I have that service! You can Connect to the Provider with port %s"%(Services_Port[Services.index(temp)]))   
            print(i)
           # New_port=(Services_Port[Services.index(temp))
            # sending data to client    
           # client.sendall(New.port)
            client.sendall(i.encode('utf-8'))
            m= False 
            
    else:
                
                print(temp)
                
                output=("NO ,I dont have that service availlable rigth now! But I have %s services on port %s "%(Services,Services_Port))
                print(output)
              #  'all I have is this: '+str(x))
                client.sendall(output.encode('utf-8')) 
                #   client.sendall(data)
#               
              #  continue 
  
   # Close the connection with the client 
client.close() 