import socket
import sys


def serverside():

    #Defines the socket that allows --> RoboDK PC <-> TCP 
    hostname = socket.gethostname() # Grabs local host name
    port = 5000 # Placeholder number, can be anything above 1024 and not in use afaik
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind((hostname,port))
    sock.listen(2) # wait for connections

    #if forwarding via the Server, below creates the socket --> TCP <-> KUKA robot
    sockRobot = socket.socket()
    sockRobot.connect(('172.31.1.147', 7000))
    
    #Waits for the RoboDK PC to connect to the TCP Server
    connection, client_add = sock.accept()
    print("Connection From: ", str(client_add))
    pack_data = ""

    while True: 
        #GetRoboDK Data
        pack_data = connection.recv(2048).decode()
        print("\nData from RoboDK:\n",pack_data)
        #If Empty
        if not pack_data:
            break
        #Extruder Commands to go to external logic board to control extruder
        if "Extrude" in pack_data:
            print("\nExtrude Command Found:\n", pack_data)
            #Code to manipulate commands goes below

        else:
            print("\nCommand Found:\n", pack_data)

        #Send data from TCP to robot
        sockRobot.sendall(pack_data.encode())
        #Get data back from robot
        data = sockRobot.recv(2048).decode()
        print("Data back from robot (handshake): ", data)
        #forward data on from TCP to RoboDK
        connection.sendall(data.encode())    
             
    connection.close()
       

def main():
    serverside()

main()
