/*
 *  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 "beingmanager.h"

#include "localplayer.h"
#include "monster.h"
#include "npc.h"
#include "player.h"
#include "playerrelations.h"
#include "configuration.h"
#include "log.h"

#include "gui/widgets/chattab.h"
#include "gui/killstats.h"
#include "gui/chat.h"
#include "gui/skilldialog.h"

#include "gui/viewport.h"

#include "net/gamehandler.h"
#include "net/net.h"

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

#include <cassert>
#include <algorithm>
#include <list>
#include <vector>

class FindBeingFunctor
{
    public:
        bool operator() (Being *being)
        {
            Uint16 other_y = y + ((being->getType() == Being::NPC) ? 1 : 0);
            const Vector &pos = being->getPosition();
            return ((int) pos.x / 32 == x &&
                    ((int) pos.y / 32 == y || (int) pos.y / 32 == other_y) &&
                    being->isAlive() &&
                    (type == Being::UNKNOWN || being->getType() == type));
        }

        Uint16 x, y;
        Being::Type type;
} beingFinder;


class FindBeingEqualFunctor
{
    public:
        bool operator() (Being *being)
        {
            return being->getId() == findBeing->getId();
        }

        Being *findBeing;
} beingEqualFinder;


class SortBeingFunctor
{
    public:
        bool operator() ( Being* being1,  Being* being2)
        {
#ifdef TMWSERV_SUPPORT
            const Vector &pos1 = being1->getPosition();
            int d1 = abs(((int) pos1.x) - x) + abs(((int) pos1.y) - y);
            const Vector &pos2 = being2->getPosition();
            int d2 = abs(((int) pos2.x) - x) + abs(((int) pos2.y) - y);
#else
            int d1 = abs(being1->getTileX() - x) + abs(being1->getTileY() - y);
            int d2 = abs(being2->getTileX() - x) + abs(being2->getTileY() - y);
#endif

            if (d1 != d2)
                return d1 < d2;
            return (being1->getName() < being2->getName());
        }
        int x,y;

} beingSorter;


bool cmpBeing(Being* being1, Being* being2)
{
    return (being1->getName() < being2->getName());
}


BeingManager::BeingManager()
{
    mSpellHeal1 = config.getValue("spellHeal1", "#lum");
    mSpellHeal2 = config.getValue("spellHeal2", "#inma");
    mSpellItenplz = config.getValue("spellItenplz", "#itenplz");
}

BeingManager::~BeingManager()
{
    clear();
}

void BeingManager::setMap(Map *map)
{
    mMap = map;
    if (player_node)
        player_node->setMap(map);
}

void BeingManager::setPlayer(LocalPlayer *player)
{
    player_node = player;
    mBeings.push_back(player);
}


Being *BeingManager::createBeing(int id, Being::Type type, int subtype)
{
    Being *being;

    switch (type)
    {
        case Being::PLAYER:
            being = new Player(id, subtype, mMap);
            break;
        case Being::NPC:
            being = new NPC(id, subtype, mMap);
            break;
        case Being::MONSTER:
            being = new Monster(id, subtype, mMap);
            break;
        case Being::UNKNOWN:
            being = new Being(id, subtype, mMap);
            break;
        default:
            assert(false);
    }

    mBeings.push_back(being);
    return being;
}

void BeingManager::destroyBeing(Being *being)
{
    mBeings.remove(being);
    viewport->clearHoverBeing(being);
    delete being;
    being = 0;
}

Being *BeingManager::findBeing(int id) const
{
    for (Beings::const_iterator i = mBeings.begin(), i_end = mBeings.end();
         i != i_end; ++i)
    {
        Being *being = (*i);
        if (being->getId() == id)
            return being;
    }
    return NULL;
}

Being *BeingManager::findBeing(int x, int y, Being::Type type) const
{
    beingFinder.x = x;
    beingFinder.y = y;
    beingFinder.type = type;

    Beings::const_iterator i = find_if(mBeings.begin(), mBeings.end(),
                                       beingFinder);

    return (i == mBeings.end()) ? NULL : *i;
}

Being *BeingManager::findBeingByPixel(int x, int y) const
{
    Beings::const_iterator itr = mBeings.begin();
    Beings::const_iterator itr_end = mBeings.end();

    y += 16;

    for (; itr != itr_end; ++itr)
    {
        Being *being = (*itr);

        int xtol = 16;
        int uptol = 16;

        if ((being->isAlive()
             || (config.getValue("targetDeadPlayers", false)
             && being->getType() == Being::PLAYER))
             && being != player_node)
        {
            if ((being->getPixelX() - xtol <= x) &&
                (being->getPixelX() + xtol > x) &&
                (being->getPixelY() - uptol <= y) &&
                (being->getPixelY() + uptol > y))
            {
                return being;
            }
        }
    }

    return NULL;
}

Being *BeingManager::findBeingByName(const std::string &name,
                                     Being::Type type) const
{
    for (Beings::const_iterator i = mBeings.begin(), i_end = mBeings.end();
         i != i_end; ++i)
    {
        Being *being = (*i);
        if (being->getName() == name &&
           (type == Being::UNKNOWN || type == being->getType()))
            return being;
    }
    return NULL;
}

Being *BeingManager::findNearestByName(const std::string &name,
                                     Being::Type type) const
{
    int dist = 0;
    Being* closestBeing = NULL;
    int x,y;

    x = player_node->getTileX();
    y = player_node->getTileY();

    for (Beings::const_iterator i = mBeings.begin(), i_end = mBeings.end();
         i != i_end; ++i)
    {
        Being *being = (*i);
        if (being->getName() == name &&
           (type == Being::UNKNOWN || type == being->getType()))
        {
            if (being->getType() == Being::PLAYER)
                return being;
            else
            {
                int d = (being->getTileX() - x) * (being->getTileX() - x)
                        + (being->getTileY() - y) * (being->getTileY() - y);

                if (validateBeing(NULL, being, type)
                    && (d < dist || closestBeing == NULL))
                {
                    dist = d;
                    closestBeing = being;
                }
            }
        }
    }
    return closestBeing;
}

const Beings &BeingManager::getAll() const
{
    return mBeings;
}

void BeingManager::logic()
{
    Beings::iterator i = mBeings.begin();
    while (i != mBeings.end())
    {
        Being *being = (*i);

        being->logic();

        if (!being->isAlive() &&
            Net::getGameHandler()->removeDeadBeings() &&
            being->getCurrentFrame() >= 20)
        {
            delete being;
            being = 0;
            i = mBeings.erase(i);
        }
        else
        {
            ++i;
        }
    }
}

void BeingManager::clear()
{
    if (player_node)
        mBeings.remove(player_node);

    delete_all(mBeings);
    mBeings.clear();

    if (player_node)
        mBeings.push_back(player_node);
}

Being *BeingManager::findNearestLivingBeing(int x, int y,
                                            int maxTileDist,
                                            Being::Type type) const
{
    //Being *closestBeing = 0;
    //int dist = 0;

    const int maxDist = maxTileDist * 32;

    return findNearestLivingBeing(NULL, maxDist, type, x, y);

/*
    Beings::const_iterator itr = mBeings.begin();
    Beings::const_iterator itr_end = mBeings.end();

    for (; itr != itr_end; ++itr)
    {
        Being *being = (*itr);
        const Vector &pos = being->getPosition();
        int d = abs(((int) pos.x) - x) + abs(((int) pos.y) - y);

        if ((being->getType() == type || type == Being::UNKNOWN)
                && (d < dist || !closestBeing)          // it is closer
                && being->isAlive())       // no dead beings
        {
//        if ((being->getType() == type || type == Being::UNKNOWN)
//                && (d < dist || closestBeing == NULL)   // it is closer
//                && (being->mAction != Being::DEAD       // no dead beings
//                || (config.getValue("targetDeadPlayers", false) && type == Being::PLAYER)))
//        {
//            if (type != Being::MONSTER || !config.getValueTargetOnlyReachable() ||  player_node->isReachable(being->getTileX(), being->getTileY()))
//            {
                dist = d;
                closestBeing = being;
//            }
        }
    }

    return (maxDist >= dist) ? closestBeing : 0;
*/
}

Being *BeingManager::findNearestLivingBeing(Being *aroundBeing, int maxDist,
                                            Being::Type type) const
{
    int x = aroundBeing->getTileX();
    int y = aroundBeing->getTileY();

    return findNearestLivingBeing(aroundBeing, maxDist, type, x, y);
}

Being *BeingManager::findNearestLivingBeing(Being *aroundBeing, int maxDist,
                                            Being::Type type, int x, int y) const
{
    Being *closestBeing = NULL;
    int dist = 0;

    maxDist = maxDist * maxDist;

    bool cycleSelect = (config.getValue("cyclePlayers", true) && type == Being::PLAYER)
                    || (config.getValue("cycleMonsters", false) && type == Being::MONSTER);

    if (cycleSelect)
    {
        std::vector<Being*> sortedBeings;

        for (Beings::const_iterator i = mBeings.begin(), i_end = mBeings.end();
             i != i_end; ++i)
        {
            Being *being = (*i);
            if (validateBeing(aroundBeing, being, type))
            {
                sortedBeings.push_back(being);
            }
        }

        // no selectable beings
        if (sortedBeings.size() == 0)
            return NULL;

        beingSorter.x = x;
        beingSorter.y = y;
        sort(sortedBeings.begin(), sortedBeings.end(), beingSorter);

        if (player_node->getTarget() == NULL)
        {
            // if no selected being, return first nearest being
            return sortedBeings.at(0);
        }

        beingEqualFinder.findBeing = player_node->getTarget();
        std::vector<Being*>::const_iterator i = find_if(sortedBeings.begin(), sortedBeings.end(),
                                           beingEqualFinder);
        if (i == sortedBeings.end() || ++i == sortedBeings.end())
        {
            // if no selected being in vector, return first nearest being
            return sortedBeings.at(0);
        }

        // we find next being after target
        return *i;
    }
    else
    {
        for (Beings::const_iterator i = mBeings.begin(), i_end = mBeings.end();
             i != i_end; ++i)
        {
            Being *being = (*i);
            int d = (being->getTileX() - x) * (being->getTileX() - x)
                    + (being->getTileY() - y) * (being->getTileY() - y);

            if (validateBeing(aroundBeing, being, type)
                && (d < dist || closestBeing == 0))
            {
//            if ((being->getType() == type || type == Being::UNKNOWN)
//                    && (d < dist || closestBeing == NULL)   // it is closer
//                    && (being->mAction != Being::DEAD       // no dead beings
//                    || (config.getValue("targetDeadPlayers", false) && type == Being::PLAYER))
//                    && being != aroundBeing)
//            {
//                if (type != Being::MONSTER || !config.getValueTargetOnlyReachable() ||  player_node->isReachable(being->getTileX(), being->getTileY()))
//                {
                    dist = d;
                    closestBeing = being;
//                }
            }
        }
        return (maxDist >= dist) ? closestBeing : 0;
    }
}

bool BeingManager::validateBeing(Being *aroundBeing, Being* being, Being::Type type) const
{
    return ((being->getType() == type || type == Being::UNKNOWN)
        && (being->isAlive()
        || (config.getValue("targetDeadPlayers", false) && type == Being::PLAYER))
        && being != aroundBeing)
        && (type != Being::MONSTER || !config.getValueTargetOnlyReachable()
        || player_node->isReachable(being->getTileX(), being->getTileY()));
}

/*
void BeingManager::HealAllTargets(Being *aroundBeing, int maxdist,
                                            Being::Type type) const
{
    // now buggy
    return;
    Being *closestBeing = NULL;
    int dist = 0;
    int x = aroundBeing->getTileX();
    int y = aroundBeing->getTileY();

    for (Beings::const_iterator i = mBeings.begin(), i_end = mBeings.end();
         i != i_end; ++i)
    {
        Being *being = (*i);
        int d = abs(being->getTileX() - x) + abs(being->getTileY() - y);

        if ((being->getType() == type || type == Being::UNKNOWN)
                && (d < dist || closestBeing == NULL)   // it is closer
                && being->mAction != Being::DEAD        // no dead beings
                && being != aroundBeing)
        {
            chatWindow->localChatInput("#inma " + being->getName());
        }
    }
}
*/

void BeingManager::healTarget(LocalPlayer* player_node)
{
    heal(player_node, player_node->getTarget());
}

void BeingManager::heal(LocalPlayer* player_node, Being* target)
{
    if (!player_node || player_node->getAttributeEffective(player_node->MATK) <= 0)
        return;

    if (target && player_node->getName() == target->getName())
    {
        if (player_node->getMP() >= 6
            && player_node->getHp() != player_node->getMaxHp())
        {
            chatWindow->localChatInput(mSpellHeal1);
        }
    }
    else if (player_node->getSkillLv(340) < 2 || player_node->getSkillLv(341) < 2)
    {
        if (player_node->getMP() >= 6)
        {
            if (target && target->getType() != Being::MONSTER)
                chatWindow->localChatInput(mSpellHeal1 + " " + target->getName());
            else if (player_node->getHp() != player_node->getMaxHp())
                chatWindow->localChatInput(mSpellHeal1);
        }
    }
    else
    {
        if (player_node->getMP() >= 10 && target && target->getType() != Being::MONSTER)
        {
            chatWindow->localChatInput(mSpellHeal2 + " " + target->getName());
        }
        else if ((!target || target->getType() == Being::MONSTER)
                 && player_node->getMP() >= 6
                 && player_node->getHp() != player_node->getMaxHp())
        {
            chatWindow->localChatInput(mSpellHeal1);
        }
    }
}

void BeingManager::itenplz()
{
    chatWindow->localChatInput(mSpellItenplz);
}

bool BeingManager::hasBeing(Being *being) const
{
    for (Beings::const_iterator i = mBeings.begin(), i_end = mBeings.end();
         i != i_end; ++i)
    {
        if (being == *i)
            return true;
    }

    return false;
}

void BeingManager::addBlock(Uint32 id)
{
    bool alreadyBlocked(false);
    for (int i=0;i < (int)blockedBeings.size(); i++)
    {
        if (id == blockedBeings.at(i))
        {
            alreadyBlocked = true;
            break;
        }
    }
    if (alreadyBlocked == false)
    {
        blockedBeings.push_back(id);
    }
}

void BeingManager::deleteBlock(Uint32 id)
{
    std::vector<Uint32>::iterator iter = blockedBeings.begin();
    while (iter != blockedBeings.end())
    {
        if (*iter == id)
        {
            iter = blockedBeings.erase(iter);
            break;
        }
    }
}

bool BeingManager::isBlocked(Uint32 id) {
    bool blocked(false);
    for (int i=0;i < (int)blockedBeings.size(); i++)
    {
        if (id == blockedBeings.at(i))
        {
            blocked = true;
            break;
        }
    }
    return blocked;
}

void BeingManager::printAllToChat() const
{
    printBeingsToChat(getAll(), "Visible on map");
}

void BeingManager::printBeingsToChat(Beings beings, std::string header) const
{
    debugChatTab->chatLog("---------------------------------------");
    debugChatTab->chatLog(header);
    for (Beings::const_iterator i = beings.begin(); i != beings.end(); i++)
    {
        const Being *being = *i;

        debugChatTab->chatLog(being->getName()
             + " (" + toString(being->getTileX()) + "," + toString(being->getTileY()) + ") "
             + toString(being->getJob()), BY_SERVER);
    }
    debugChatTab->chatLog("---------------------------------------");
}

void BeingManager::printBeingsToChat(std::vector<Being*> beings, std::string header) const
{
    debugChatTab->chatLog("---------------------------------------");
    debugChatTab->chatLog(header);

    std::vector<Being*>::iterator i;
    for (i=beings.begin(); i!=beings.end(); ++i)
    //for (Beings::const_iterator i = beings.begin(); i != beings.end(); i++)
    {
        const Being *being = *i;

        debugChatTab->chatLog(being->getName()
             + " (" + toString(being->getTileX()) + "," + toString(being->getTileY()) + ") "
             + toString(being->getJob()), BY_SERVER);
    }
    debugChatTab->chatLog("---------------------------------------");
}

Being *BeingManager::createGhost(int id, Being::Type type, int subtype)
{
    debugChatTab->chatLog("GHOST detected: "
         + toString(id) + "," + toString(type) + ","
         + toString(subtype), BY_SERVER);
    return NULL;
}

void BeingManager::destroyRain()
{
    Beings::iterator i = mBeings.begin();
    while (i != mBeings.end())
    {
        if ((*i)->getJob() == 127 && (*i)->getName() == "")
        {
            Being *being = (*i);
            delete being;
            being = 0;
            i = mBeings.erase(i);
        }
        else
        {
            ++i;
        }
    }
}

void BeingManager::getPlayerNames(std::vector<std::string> &names,
                                  bool npcNames)
{
    Beings::iterator i = mBeings.begin();
    names.clear();

    while (i != mBeings.end())
    {
        Being *being = (*i);
        if ((being->getType() == Being::PLAYER
             || (being->getType() == Being::NPC && npcNames))
            && being->getName() != "")
        {
            names.push_back(being->getName());
        }
        ++i;
    }
}

void BeingManager::updatePlayerNames()
{
    Beings::iterator i = mBeings.begin();

    while (i != mBeings.end())
    {
        Being *being = (*i);
        if (being->getType() == Being::PLAYER && being->getName() != "")
            being->updateName();
        ++i;
    }
}

void BeingManager::parseLevels(std::string levels)
{
    levels += ", ";
    unsigned int f = 0;
    unsigned long pos = 0;
    const std::string brkEnd = "), ";

    pos = levels.find(brkEnd, f);
    while (pos != std::string::npos)
    {
        std::string part = levels.substr(f, pos - f);
        if (part.empty())
            break;
        unsigned long bktPos = part.rfind("(");
        if (bktPos != std::string::npos)
        {
            Being *being = findBeingByName(part.substr(0, bktPos), Being::PLAYER);
            if (being)
                being->setLevel(atoi(part.substr(bktPos + 1).c_str()));
        }
        f = pos + brkEnd.length();
        pos = levels.find(brkEnd, f);
    }
}

