import json
from ws4py.client.threadedclient import WebSocketClient


class ExampleClient(WebSocketClient):

    def __init__(self, url):
        super().__init__(url)
        self.name = "Agent1"

    def opened(self):
        pass
        # self.send(json.dumps({"name": self.name}))w

    def closed(self, code, reason=None):
        print("Closed down", code, reason)

    def received_message(self, message):
        content = json.loads(str(message))
        print(content)
        if "action_list" in content and content["action_list"]:
            '''     card_type = random.choice(list(content["action_list"].keys()))
                print("Choose type ", card_type)
                rank = random.choice(list(content["action_list"][card_type].keys()))
                action = random.choice(list(content["action_list"][card_type][rank]))
                print("Choose action:", action)
                self.send(json.dumps({"action": action, "type": card_type, "rank": rank}))
            '''
            transform = {'A': 14, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8,
                          '9': 9, '10': 10, 'J': 11, 'Q': 12, 'K': 13, 'JOKER': 15, 'PASS': 10000000,
                          'Straight': 10, 'TripsPair': 1, 'ThreeWithTwo': 10, 'ThreePair': 1, 'Trips': 50,
                          'Pair': 100, 'Single': 1000,'Bomb':10000,'StraightFlush':100000,'back':1 ,'tribute':1}
            minscore = 10000000
            ans_action = [[0, 'PASS']]
            ans_card_type = 'PASS'
            ans_rank = 'PASS'
            if ( content["current_player"] + content["index"] ) % 2 != 0 or  content["current_player"] == content["index"]  :
                for card_type in list(content["action_list"].keys()):
                    for rank in list(content["action_list"][card_type].keys()):
                        for action in list(content["action_list"][card_type][rank]):
                            score = transform[card_type]  * transform[rank]
                            if score <= minscore:
                                minscore = score
                                ans_card_type = card_type
                                ans_rank = rank
                                ans_action = action
            self.send(json.dumps({"action": ans_action, "type": ans_card_type, "rank": ans_rank}))


if __name__ == '__main__':
    try:
        ws = ExampleClient('ws://127.0.0.1:23456/game/bot1')
        ws.connect()
        ws.run_forever()
    except KeyboardInterrupt:
        ws.close()
