/*
 * ServerAnswerXML.j
 * RouteIntelligence
 *
 * Created by P. Miranda on Sept 11, 2010.
 * Copyright 2010, Predisoft Internacional S.A. All rights reserved.
 */



@import <Foundation/CPObject.j>
@import "ServerRecord.j"

 

@implementation ServerAnswerXML : CPObject {

    id          recs;
	id          titl;
	id          tota;
	id          systValu;
	id          systCode;
	id          typeAnsw;
	id          mssg;
	id          erro;	
	id          htmlCode;
	
}




- (CPString) contentsOfTag:(CPString)aTag inText:(CPString)aText {

    // defino los String de principio y fin del bloque
    var tagInit = [CPString stringWithFormat:@"<%@>",aTag];      
	var tagFina = [CPString stringWithFormat:@"</%@>",aTag];
//	console.log("TAG INIT " + aTag + "  TEXT =" + aText);
	// Busco las posiciones de los Tags en el bloque.
    var blckStar = [aText rangeOfString:tagInit];
	var blckFina = [aText rangeOfString:tagFina];

	// Investigo si existen ambos Tags en el Tag Block
	// de lo contrario envio un mensaje de tag mal codificado
	
	if ( blckStar.location==CPNotFound || blckFina.location==CPNotFound )
	   return nil;
	
	var finalRange = CPMakeRange(blckStar.location+[tagInit length],blckFina.location-blckStar.location-[tagInit length]);

	var content = [aText substringWithRange:finalRange];
	return content;
	
}



- (int) count {
   return [recs count];
}



- (CPArray) elements {
	return recs;
}



- (int) globalCount {
    return tota;
}



- (id) initWithAnswer:(CPString)_answ {
	[super init];

//        _answ = [CPData dataWithRawString:_answ];
	// Se declaran los separadores de fila y de columna
	var lineSepa = @"#nl";
	var coluSepa = @"#nv";

	
	if ( recs )
	     [recs release];
	recs = [[CPMutableArray alloc] init];
	
	typeAnsw = [self contentsOfTag:@"type" inText:_answ];

	if ( [typeAnsw isEqualToString:@"result"] ) {
	     // Encuentro el total de registros en caso que este paginado
		 // Si no esta paginado se devuelve un valor -1
	     var xTota = [self contentsOfTag:@"total" inText:_answ];
		 xTota = -1;
		 if ( xTota )
	          tota = [xTota intValue];

		 // Encuentro el titulo o array de nombres de los campos
		 var xFields = [self contentsOfTag:@"fields" inText:_answ];
		 if ( xFields )
		      titl = [[CPArray alloc] initWithArray:[xFields componentsSeparatedByString:coluSepa]]; //coluSepa????

		 // Encuentro la matriz de resultados
		 var xValues = [self contentsOfTag:@"data" inText:_answ];

		 // Obtengo el arreglo de filas o lineas de resultados
		 if ( xValues ) {
		      var arra = [xValues componentsSeparatedByString:lineSepa];

			  var i;
			  var arraCoun= [arra count];
			  var arroCoun= 0;
			  for ( i=0; i<arraCoun; i++ ) {
			       var arro = [[arra objectAtIndex:i] componentsSeparatedByString:coluSepa];
		           if ( arro ) {
				      if ( arroCoun==0 || arroCoun==[arro count] ) {
		               var sr = [[ServerRecord alloc] initWithKeyList:titl valueList:arro];
			          [recs addObject:sr];
			          }
			          arroCoun= [arro count];
		           }				   
		      }
		 }
	}
	
	else if ( [typeAnsw isEqualToString:@"system"] ) {
	     mssg = [self contentsOfTag:@"message" inText:_answ];
		 erro = [self contentsOfTag:@"error" inText:_answ];
		 systCode = [self contentsOfTag:@"code" inText:_answ];
		 systValu = [self contentsOfTag:@"value" inText:_answ];
		} 

			  
	else if ( [typeAnsw isEqualToString:@"html"] ) {	

	     htmlCode = [self contentsOfTag:@"value" inText:_answ];
		 htmlCode = [htmlCode stringByReplacingOccurrencesOfString:@"<![CDATA[" withString:@""];
		 htmlCode = [htmlCode substringToIndex:[htmlCode length]-3];

	}

	return self;
}



- (id) objectAtIndex:(int)inde {
	return [recs objectAtIndex:inde];
}


- (CPString) type {
    return typeAnsw;
}

- (var) message {
       if ( erro )
	        return nil;
	return erro;
}

- (CPString) errorMessage {
   var empty = @"";
   if ( [typeAnsw isEqualToString:@"system"] ) {
       if ( erro )
	        return systValu;
	}
   return empty;
}

- (CPString) systemMessage {
   var empty = @"";
   if ( [typeAnsw isEqualToString:@"system"] ) {
       if ( mssg )
	        return systValu;
	}
   return empty;
}


- (CPString) htmlPage {
    var empty = @"";
   if ( [typeAnsw isEqualToString:@"html"] ) {
       if (htmlCode)
	        return htmlCode;
	}
   return empty;  
}

@end
