/*
 *  The Mana Client
 *  Copyright (C) 2004-2009  The Mana World Development Team
 *  Copyright (C) 2009-2010  The Mana Developers
 *
 *  This file is part of The Mana Client.
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "gui/inventorywindow.h"

#include "inventory.h"
#include "item.h"
#include "localplayer.h"
#include "units.h"
#include "keyboardconfig.h"

#include "gui/itemamount.h"
#include "gui/setup.h"
#include "gui/sdlinput.h"
#include "gui/theme.h"
#include "gui/viewport.h"

#include "gui/widgets/button.h"
#include "gui/widgets/itemcontainer.h"
#include "gui/widgets/label.h"
#include "gui/widgets/layout.h"
#include "gui/widgets/progressbar.h"
#include "gui/widgets/scrollarea.h"

#include "net/inventoryhandler.h"
#include "net/net.h"

#include "resources/iteminfo.h"

#include "utils/gettext.h"
#include "utils/stringutils.h"

#include <guichan/font.hpp>
#include <guichan/mouseinput.hpp>

#include <string>

InventoryWindow::InventoryWindow(int invSize):
    Window(_("Inventory")),
    mMaxSlots(invSize),
    mSplit(false),
    mItemDesc(false)
{
    setWindowName("Inventory");
    setupWindow->registerWindowForReset(this);
    setResizable(true);
    setCloseButton(true);
    setSaveVisible(true);

    setDefaultSize(387, 307, ImageRect::CENTER);
    setMinWidth(316);
    setMinHeight(179);
    addKeyListener(this);

    std::string longestUseString = getFont()->getWidth(_("Equip")) >
                                   getFont()->getWidth(_("Use")) ?
                                   _("Equip") : _("Use");

    if (getFont()->getWidth(longestUseString) <
        getFont()->getWidth(_("Unequip")))
    {
        longestUseString = _("Unequip");
    }

    mUseButton = new Button(longestUseString, "use", this);
    mUseButton2 = new Button(longestUseString, "equip", this);
    mDropButton = new Button(_("Drop..."), "drop", this);
    mSplitButton = new Button(_("Split"), "split", this);
    mOutfitButton = new Button(_("Outfits"), "outfit", this);
    mItems = new ItemContainer(player_node->getInventory());
    mItems->addSelectionListener(this);

    gcn::ScrollArea *invenScroll = new ScrollArea(mItems);
    invenScroll->setHorizontalScrollPolicy(gcn::ScrollArea::SHOW_NEVER);

    mTotalWeight = -1;
    mMaxWeight = -1;
    mUsedSlots = -1;

    mSlotsLabel = new Label(_("Slots:"));
    mWeightLabel = new Label(_("Weight:"));

    mSlotsBar = new ProgressBar(0.0f, 100, 20, Theme::PROG_INVY_SLOTS);
    mWeightBar = new ProgressBar(0.0f, 100, 20, Theme::PROG_WEIGHT);

    place(0, 0, mWeightLabel).setPadding(3);
    place(1, 0, mWeightBar, 3);
    place(4, 0, mSlotsLabel).setPadding(3);
    place(5, 0, mSlotsBar, 2);
    place(0, 1, invenScroll, 7).setPadding(3);
    place(0, 2, mUseButton);
    place(1, 2, mUseButton2);
    place(2, 2, mDropButton);
    place(3, 2, mSplitButton);
    place(6, 2, mOutfitButton);

    Layout &layout = getLayout();
    layout.setRowHeight(1, Layout::AUTO_SET);

    loadWindowState();
}

InventoryWindow::~InventoryWindow()
{
}

void InventoryWindow::logic()
{
    Window::logic();

    if (!isVisible() || !player_node)
        return;

    // It would be nicer if this update could be event based, needs some
    // redesign of InventoryWindow and ItemContainer probably.
    updateButtons();

    const int usedSlots = player_node->getInventory()->getNumberOfSlotsUsed();

    if (mMaxWeight != player_node->getMaxWeight() ||
        mTotalWeight != player_node->getTotalWeight() ||
        mUsedSlots != usedSlots)
    {
        mTotalWeight = player_node->getTotalWeight();
        mMaxWeight = player_node->getMaxWeight();
        mUsedSlots = usedSlots;

        // Adjust progress bars
        mSlotsBar->setProgress((float) mUsedSlots / mMaxSlots);
        mWeightBar->setProgress((float) mTotalWeight / mMaxWeight);

        mSlotsBar->setText(strprintf("%d/%d", mUsedSlots, mMaxSlots));
        mWeightBar->setText(strprintf("%s/%s",
                                    Units::formatWeight(mTotalWeight).c_str(),
                                    Units::formatWeight(mMaxWeight).c_str()));
    }
}

void InventoryWindow::action(const gcn::ActionEvent &event)
{
    if (event.getId() == "outfit")
    {
        extern Window *outfitWindow;
        if (outfitWindow)
        {
            outfitWindow->setVisible(!outfitWindow->isVisible());
            if (outfitWindow->isVisible())
                outfitWindow->requestMoveToTop();
        }
    }

    Item *item = mItems->getSelectedItem();

    if (!item)
        return;

    if (event.getId() == "use")
    {
        if (item->isEquipment())
        {
            if (item->isEquipped())
                Net::getInventoryHandler()->unequipItem(item);
            else
                Net::getInventoryHandler()->equipItem(item);
        }
        else
            Net::getInventoryHandler()->useItem(item);
    }
    if (event.getId() == "equip")
    {
        if (!item->isEquipment())
        {
            if (item->isEquipped())
                Net::getInventoryHandler()->unequipItem(item);
            else
                Net::getInventoryHandler()->equipItem(item);
        }
        else
            Net::getInventoryHandler()->useItem(item);
    }
    else if (event.getId() == "drop")
    {
        if (StorageWindow::isActive())
        {
            Item *item = mItems->getSelectedItem();

            if(!item)
                return;

            StorageWindow::addStore(item, item->getQuantity());
        }
        else
        {
            ItemAmountWindow::showWindow(ItemAmountWindow::ItemDrop, this, item);
        }
    }
    else if (event.getId() == "split")
    {
        ItemAmountWindow::showWindow(ItemAmountWindow::ItemSplit, this, item,
                                 (item->getQuantity() - 1));
    }
}

Item *InventoryWindow::getSelectedItem() const
{
    return mItems->getSelectedItem();
}

void InventoryWindow::mouseClicked(gcn::MouseEvent &event)
{
    Window::mouseClicked(event);

    if (event.getButton() == gcn::MouseEvent::RIGHT)
    {
        Item *item = mItems->getSelectedItem();

        if (!item)
            return;

        /* Convert relative to the window coordinates to absolute screen
         * coordinates.
         */
        const int mx = event.getX() + getX();
        const int my = event.getY() + getY();
        if (viewport)
            viewport->showPopup(this, mx, my, item);
    }

    if (event.getButton() == gcn::MouseEvent::LEFT)
    {
        if (StorageWindow::isActive() &&
            keyboard.isKeyActive(keyboard.KEY_EMOTE))
        {
            Item *item = mItems->getSelectedItem();

            if(!item)
                return;

            StorageWindow::addStore(item, item->getQuantity());
        }
    }
}

void InventoryWindow::keyPressed(gcn::KeyEvent &event)
{
    switch (event.getKey().getValue())
    {
        case Key::LEFT_SHIFT:
        case Key::RIGHT_SHIFT:
            mSplit = true;
            break;
        default:
            break;
    }
}

void InventoryWindow::keyReleased(gcn::KeyEvent &event)
{
    switch (event.getKey().getValue())
    {
        case Key::LEFT_SHIFT:
        case Key::RIGHT_SHIFT:
            mSplit = false;
            break;
        default:
            break;
    }
}

void InventoryWindow::valueChanged(const gcn::SelectionEvent &event _UNUSED_)
{
    if (mSplit && Net::getInventoryHandler()->canSplit(mItems->getSelectedItem()))
    {
        Item *item = mItems->getSelectedItem();

        if (item)
        {
            ItemAmountWindow::showWindow(ItemAmountWindow::ItemSplit, this, item,
                                 (item->getQuantity() - 1));
        }
    }
}


void InventoryWindow::setSplitAllowed(bool allowed)
{
    mSplitButton->setVisible(allowed);
}

void InventoryWindow::updateButtons()
{
    const Item *selectedItem = mItems->getSelectedItem();

    if (!selectedItem || selectedItem->getQuantity() == 0)
    {
        mUseButton->setEnabled(false);
        mUseButton2->setEnabled(false);
        mDropButton->setEnabled(false);
        return;
    }

    mUseButton->setEnabled(true);
    mUseButton2->setEnabled(true);
    mDropButton->setEnabled(true);

    if (selectedItem->isEquipment())
    {
        if (selectedItem->isEquipped())
            mUseButton->setCaption(_("Unequip"));
        else
            mUseButton->setCaption(_("Equip"));
        mUseButton2->setCaption(_("Use"));
    }
    else
    {
        mUseButton->setCaption(_("Use"));
        if (selectedItem->isEquipped())
            mUseButton2->setCaption(_("Unequip"));
        else
            mUseButton2->setCaption(_("Equip"));
    }

    if (StorageWindow::isActive())
    {
        mDropButton->setCaption(_("Store"));
    }
    else
    {
        if (selectedItem->getQuantity() > 1)
            mDropButton->setCaption(_("Drop..."));
        else
            mDropButton->setCaption(_("Drop"));
    }

    if (Net::getInventoryHandler()->canSplit(selectedItem))
        mSplitButton->setEnabled(true);
    else
        mSplitButton->setEnabled(false);
}
