from core.ui import DialogUi

from siege import game
from siege.io import DataStream
from siege.log import Log
from siege.network import Message
from siege.util import PixelRect


class TravelUi(DialogUi):
    def __init__(self, player):
        self.player = player
        windowSize = game.render.getWindowSize()
        width = 400
        height = 375
        x = 25
        y = (windowSize.y / 2) - (3 * height / 4)
        DialogUi.__init__(self, 'travel', PixelRect(x, y, width, height))
        self.load('html/travel.html')
        self.view.register('populate', self._handlePopulate)
        self.view.register('attune', self._handleAttune)
        self.view.register('travel', self._handleTravel)
        self.shardContent = game.content.get("way_shard")
        inventory = player.entity.inventory
        for index in xrange(inventory.capacity):
            if inventory.exists(index):
                inventory.getBag(index).onChange.listen(self._handleItemChanged)

    def updateCrystals(self, attuned, current, crystals):
        commands = []
        commands.append("App.info.set('attuned', {});".format(attuned))
        commands.append("App.info.current.set('name', '{}');".format(current.name))
        commands.append("App.info.current.set('id', {});".format(current.entityId))
        commands.append("App.info.current.set('icon', '{}');".format(self._getIconForCrystal(current)))
        commands.append("App.info.current.set('cost', {});".format(current.cost))
        commands.append("App.info.crystals.clear();")
        crystals.sort(key=lambda crystal: crystal.cost)
        for crystal in crystals:
            data = "name: '{}', id: {}, distance: {}, cost: {}".format(crystal.name, crystal.entityId, crystal.distance, crystal.cost)
            commands.append("var crystal = App.Crystal.create({{ {} }});".format(data))
            commands.append("crystal.set('icon', '{}');".format(self._getIconForCrystal(crystal)))
            commands.append("App.info.crystals.pushObject(crystal);")
        self.view.execute(commands)

    def _getIconForCrystal(self, crystal):
        return "../images/way_crystal_{}.png".format(crystal.biome.lower())

    def _handlePopulate(self, view, args):
        self._updateShardCount()

    def _handleAttune(self, view, args):
        entityId = args[1].toInteger()
        Log.info("Attune to crystal: {}".format(entityId))
        packet = DataStream(Message.TRAVEL_ATTUNE)
        packet.writeUint32(entityId)
        game.network.getClient().send(packet)

    def _handleTravel(self, view, args):
        entityId = args[1].toInteger()
        Log.info("Travel to crystal: {}".format(entityId))
        packet = DataStream(Message.TRAVEL_SELECT)
        packet.writeUint32(entityId)
        game.network.getClient().send(packet)

    def _handleItemChanged(self, bagIndex, index, previous, item):
        if previous.content == self.shardContent or item.content == self.shardContent:
            self._updateShardCount()

    def _updateShardCount(self):
        shardCount = self.player.entity.inventory.getContentQuantity(self.shardContent)
        self.view.execute("App.info.set('availableShards', {});".format(shardCount))
