#include "Consumable.h"

#include "../util/fileUtils.h"
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/xpath.h>
#include <libxml/xpathInternals.h>

using namespace std;

Consumable :: Consumable ()
{
  playerAbilityID = "NULL_INDEX";
}

Consumable :: ~Consumable ()
{
}

const string & Consumable :: getPlayerAbilityName ()
{
  return playerAbilityID;
}

void Consumable :: setPlayerAbilityName (const string & x)
{
  playerAbilityID = x;
}

uint8_t Consumable :: loadConsumable (const string & id)
{
  //reads the xml file and loads stats into the object.
  //0 : Consumable is now loaded.
  //1 : Error while loading

  if (id.empty() || id == "NULL_INDEX")
    return 1;

  xmlDocPtr doc;
  xmlXPathContextPtr xpathCtx;

  string xpathStart="/ItemManifest/Consumable[@ID='";
  xpathStart+=id;
  xpathStart+="']";

  if (!prepareXMLFile (doc, xpathCtx, "resources/game/ItemManifest.xml", xpathStart))
    {
      return false;
    }

  bool tempBool = xPathExists (doc, xpathCtx, xpathStart, "", "");
  if (tempBool)
    tempBool = loadConsumableHelper (doc, xpathCtx, xpathStart);

  xmlXPathFreeContext(xpathCtx);
  xmlFreeDoc(doc);

  if (!tempBool)
    return 3;

  setItemID (id);
  return 0;
}

bool Consumable :: loadConsumableHelper (xmlDocPtr doc, xmlXPathContextPtr xpathCtx, const string & xpath)
{
  xmlChar * element;
  int temp;
  string gab;

  element = getFirstElementUsingXPath (doc, xpathCtx, xpath, "/Price", "");
  if (element == NULL)
    temp = 0;
  else
    temp = int(xmlXPathCastStringToNumber(element));
  xmlFree (element);
  setPrice (temp);

  element = getFirstElementUsingXPath (doc, xpathCtx, xpath, "/AbilityName", "");
  if (element==NULL)
    return false;
  else
    {
      gab.assign ((const char *)element);
      xmlFree (element);
    }
  setPlayerAbilityName (gab);
  return true;
}
