/*
 * Author:
 *         Kendy Kutzner <kutzner@ira.uka.de>
 *
 * (c) 2005 Research Group Dr. Fuhrmann, University of Karlsruhe, Germany
 * All rights reserved.
 *
 * $Id: noderef.cc,v 1.8 2005/11/21 10:46:57 kutzner Exp $
 *
 */

#include <sstream>
using namespace std;

#include "assert.h"

#include "igor.h"
#include "noderef.h"

noderef::noderef()
:id(),transport(){
}

noderef::noderef(id i, transport t)
:id(i) , transport(t){
}

noderef::noderef(id i)
:id(i),transport(){
}

noderef::noderef(string s){
	int size = s.size();
	if (size < 5){ // open, thing, space, thing, close
		noderef();
		return;
	}
	int lbrpos = s.find('(');
	int spacepos = s.find(' ');
	int rbrpos = s.find(')');
	if (!((lbrpos == 0 ) &&
		(lbrpos < spacepos) && 
		(spacepos < rbrpos) &&
		(rbrpos < size) &&
		(rbrpos + 1 == size))){
		noderef();
		return;
	}
	parseid(s.substr(lbrpos+1, spacepos-1));
	parsetransport(s.substr(spacepos+1, rbrpos-1));
}

string
noderef::tostring() const {
	stringstream s;
	s << '(';
	s << id::tostring();
	s << ' ';
	s << transport::tostring();
	s << ')';
	return s.str();
}

void
noderef::update(noderef prop){
	if (!(dynamic_cast<id*>(&prop))->empty()){
		change(prop);
	}
	if (!(dynamic_cast<transport*>(&prop))->empty()){
		sethost(prop.host());
		setport(prop.port());
	}
}

void
noderef::update(string s){
	noderef prop(s);
	if (!prop.empty()){ // check noderef syntax
		update(prop);
		return;
	} else { 
		id i(s); // try to read it as id
		if (!i.empty()){ 
			parseid(s);
			return;
		} else {
			transport t(s); // try to read it as transport
			if (!(t.empty())){
				parsetransport(s);
				return;
			}
		}
	}
	assert(0);
}

bool 
noderef::empty() const {
	if (id::empty() || transport::empty()) {
		return true;
	}
	return false;
}

bool
noderef::sameid(noderef & other) const {
	return id::operator==(other);
}

bool
noderef::sametransport(noderef & other) const {
	return transport::operator==(other);
}
