import socket
import sys
import time
import traceback

print('this is XBOX gamepad')
try:
    import vgamepad
    from sbc.visual_buttons import XBOXS_Buttons


    def uniq_xbox_gamepad_runner():

        port = 0
        host = '127.0.0.1'

        # s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # s.bind((host, port))
        #
        xbox_buttons = XBOXS_Buttons()
        # bind the socket with server and port number
        for nnn in range(5000, 5500):
            try:
                # create a socket at server side using TCP / IP protocol
                s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                s.bind((host, nnn))
                port = nnn
                print('success')
                break
            except Exception as error:
                print('failed')
                time.sleep(.1)
        if port == 0:
            print('Error : Can not create xbox game pad')
            time.sleep(20)
            return
        with open('gamepad_port.txt', 'w') as gamepad_port_file:
            gamepad_port_file.write(str(port))
        # allow maximum 1 connection to  the socket
        s.listen(3)
        while True:
            try:
                conn, addr = s.accept()
                data = conn.recv(1024).decode()
                # if not data:
                #     break
                if data == 'killsrv':
                    conn.close()
                    sys.exit()
                else:
                    if data:
                        eval(f'xbox_buttons.{data}')
                        conn.send('success'.encode())
                    else:
                        print("CONNECTION FROM:", str(addr))
            except:
                print(traceback.format_exc())
                time.sleep(1)


    uniq_xbox_gamepad_runner()
except:
    traceback.print_exc()
    print()
    print()
    print()
    # input('-- press Enter to close --')

# todo : for convert this file to .exe enter bellow in terminal
# ViGEmClient.dll is for windows 64 bit
# python -m PyInstaller --onefile --icon=utils\\xbox_gamepad_icon.ico --add-binary="ViGEmClient.dll;." .\uniq_xbox_gamepad.py