// Cyphesis Online RPG Server and AI Engine
// Copyright (C) 2008 Alistair Riddoch
//
// 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
// (at your option) 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, write to the Free Software Foundation,
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA


#include "Router.h"

#include "log.h"

#include <Atlas/Objects/Anonymous.h>
#include <Atlas/Objects/Operation.h>

Router::Router(RouterId id) :
		RouterIdentifiable(std::move(id)) {
}

Router::~Router() = default;

void Router::buildError(const Operation& op,
						const std::string& errstring,
						const Operation& e,
						const std::string& to) {
	std::vector<Atlas::Objects::Root>& args = e->modifyArgs();

	Atlas::Objects::Entity::Anonymous arg1;
	arg1->setAttr("message", errstring);
	args.push_back(arg1);
	args.push_back(op);

	if (!to.empty()) {
		if (!op->isDefaultSerialno()) {
			e->setRefno(op->getSerialno());
		}
		e->setTo(to);
	}
}

void Router::error(const Operation& op,
				   const std::string& errstring,
				   OpVector& res,
				   const std::string& to) const {
	Atlas::Objects::Operation::Error e;

	spdlog::debug("ERROR generated by router with '{}' with message \"{}\"",
				  getIdAsString(), errstring);

	buildError(op, errstring, e, to);

	res.push_back(e);
}

void Router::clientError(const Operation& op,
						 const std::string& errstring,
						 OpVector& res,
						 const std::string& to) const {
	Atlas::Objects::Operation::Error e;

	buildError(op, errstring, e, to);

	res.push_back(e);
}
