import ObjectItem
from Log import LOG
from Reader import reader
from ObjectItem import obj_ref
from i18n import i18n_fr

class Chinq():
    def __init__(self, server):
        self.cards = []
        self.item = None
        self.to_remove = []
        self.server = server

    def add_card(self):
        reader.readBoolean()
        item = ObjectItem.ObjectItem()
        if self.to_remove != []:
            for to_rm in self.to_remove:
                for card in self.cards[::]:
                    if card[0] == to_rm:
                        self.cards.remove(card)
        self.to_remove = []
        for card in self.cards[::]:
            if card[1] == item.object_gid:
                self.cards.remove(card)
        self.cards.append([item.object_uid, item.object_gid])
        if len(self.cards) == 5:
            print ("Current cards: ")
            for item in self.cards:
                print ("    - " + obj_ref.get_object_name(item[1]))
            tmp_cards = sorted(self.cards, key=lambda card: card[1])
            data = {
                'c0': tmp_cards[0][1],
                'c1': tmp_cards[1][1],
                'c2': tmp_cards[2][1],
                'c3': tmp_cards[3][1],
                'c4': tmp_cards[4][1],
            }
            ret = self.server.ask_server(data, "which_item/")
            if ret.status_code == 200:
                LOG.info(f"Expected item: {ret.json()['name']}")
            elif ret.status_code == 201:
                LOG.info("Item not found in DB")

    def remove_card(self):
        self.to_remove.append(ObjectItem.ObjectItemRemoved().object_uid)

    def add_result(self):
        result = reader.readByte()
        self.item = ObjectItem.ObjectItem(from_fm=True)
        string = ""
        self.cards = sorted(self.cards, key=lambda card: card[1])
        for val in self.cards[-5:]:
            string += f"            - {val[1]}\n"
        LOG.info(f"""
        Crafted {self.item.name} with:
{string}""")
        data = {
            'c0': self.cards[0][1],
            'c1': self.cards[1][1],
            'c2': self.cards[2][1],
            'c3': self.cards[3][1],
            'c4': self.cards[4][1],
            'item': self.item.object_gid
        }
        self.server.send_to_server(data, 'add_craft/', server_req=False)
        self.item = None
        self.cards = []
