/*   -*- coding: utf-8 -*-  */
/****************************************************************************
*
*      Module  : SxPath
*      Fichier : SxPathEvalTools.c
*      Auteur  : J. Ducloy
*
***************************************************************************/

#include <stdio.h>
#include <string.h>
#include "SxPath.h"
#include "Except.h"
#include <stdlib.h>

SxmlNode *SxPathEvalTestNameInAxis(SxmlNode *testNameNode, SxmlNode *x1, SxmlNode *pos)
{
  char *name1;
  name1=SxmlLeafText(testNameNode);
  if(strcmp(name1,SxmlNodeName(x1))==0)
    {
      SxmlContainerIntegerIncr(pos);
      return x1;
    }
  else return (NULL);
}

SxmlNode *SxPathEvalOnePredicate( SxmlNode *predicateItem, SxmlNode *x1, SxmlNode *pos)
{
  int testType;
  testType=SxmlNodeSubType(predicateItem);
  switch(testType)
    {
    case SXPATH_PREDICATE_POSITION:
      {
	int posRef;
	posRef=atoi(SxmlLeafText(predicateItem));
	if (posRef==SxmlContainerIntegerValue(pos))return x1;
	return NULL;
      }

    case  SXPATH_RELATIONAL_EXPR:
      {
	SxmlNode *op1;
	SxmlNode *op2;
	SxmlNode *xc1;
	char *targetTag;
	int targetValue;
	char *operator;
	op1=SxmlFirstChild(predicateItem);
	op2=SxmlLastChild(predicateItem);
	operator=SxmlGetAttribute(predicateItem,"operator");
	targetTag=SxmlLeafText(op1);
	targetValue=atoi(SxmlLeafText(op2));
	xc1=SxmlGetFirstChildByTagName(x1, targetTag);
	while (xc1)
	  {
	    if (SxmlIsLeaf(xc1))
	      {
		int nodeValue;
		nodeValue=atoi(SxmlLeafText(xc1));
		if (strcmp(operator,"gt")==0)
		  {
		    if (nodeValue>targetValue) return x1;
		  }
		else if (nodeValue<targetValue) return x1;
	      }
	    xc1=SxmlGetNextSiblingByTagName(xc1, targetTag);
	  }
	return NULL;
      }

    case SXPATH_PREDICATE_ATTRIBUTE:
      {
	char* a1;
	char *v1;
	a1=SxmlGetAttribute(predicateItem,"name");
	v1=SxmlLeafText(predicateItem);
	if(SxmlHasAttribute(x1,a1,v1))return x1;
	else return NULL;
      }
    default:
      ExceptSetError("SxPathAxis","NY"," ","predicate ","not yet implemented",2);
      return NULL;
    }
}

SxmlNode *SxPathEvalListPredicates( SxmlNode *firstPredicate, SxmlNode *x1, SxmlNode *pos)
{
  SxmlNode *resu;
  SxmlNode *nextPredicate;

  if(!firstPredicate)return NULL;
    
  resu=SxPathEvalOnePredicate(firstPredicate, x1, pos);
  if (!resu) return NULL;
  nextPredicate=SxmlNextSibling(firstPredicate);
  if (nextPredicate) return SxPathEvalListPredicates(nextPredicate, x1, pos);
  return x1;
}
