#external_receiver.py
import socket

def connect():
    receiver_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    receiver_socket.settimeout(15)  # Increase timeout to 15 seconds
    receiver_socket.connect(('localhost', 5555))
    receiver_socket.send("RECEIVER".encode())
    print("Connected to GSM simulator as RECEIVER")

    while True:
        try:
            data = receiver_socket.recv(1024).decode().strip()
            if not data:
                print("No data received. Connection closed.")
                break
            if data == "RINGING":
                print("Incoming call... ringing")
            elif data == "CALL_END":
                print("Call ended by caller.")
                break
            elif data == "CALL_DROPPED":
                print("Call dropped by network.")
                break
            else:
                print(f"Received: {data}")
        except socket.timeout:
            print("Timed out waiting for data.")
            break
        except Exception as e:
            print(f"Receiver error: {e}")
            break

    receiver_socket.close()

if __name__ == "__main__":
    connect()