// ---------------------------------------------------------------------------
// - NwgCalls.cpp                                                            -
// - afnix:nwg module - specific calls implementation                        -
// ---------------------------------------------------------------------------
// - This program is free software;  you can redistribute it  and/or  modify -
// - it provided that this copyright notice is kept intact.                  -
// -                                                                         -
// - 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.  In no event shall -
// - the copyright holder be liable for any  direct, indirect, incidental or -
// - special damages arising in any way out of the use of this software.     -
// ---------------------------------------------------------------------------
// - copyright (c) 1999-2008 amaury darsch                                   -
// ---------------------------------------------------------------------------

#include "Uri.hpp"
#include "Cons.hpp"
#include "Vector.hpp"
#include "NwgCalls.hpp"
#include "Exception.hpp"

namespace afnix {

  // -------------------------------------------------------------------------
  // - public section                                                        -
  // -------------------------------------------------------------------------

  // normalize a uri name by adding a scheme if any

  Object* nwg_nrmunm (Runnable* robj, Nameset* nset, Cons* args) {
    // evaluate the arguments
    Vector* argv = Vector::eval (robj, nset, args);
    long    argc = (argv == nilp) ? 0 : argv->length ();
    try {
      if (argc == 1) {
	String name = argv->getstring (0);
	delete argv; argv = nilp;
	return new String (Uri::nrmname (name));
      }
      if (argc == 2) {
	String name = argv->getstring (0);
	bool   flag = argv->getbool   (1);
	delete argv; argv = nilp;
	if (flag == true) {
	  Uri uri = Uri::nrmname (name);
	  uri.nrmauth ();
	  return new String (uri.getname ());
	} else {
	  return new String (Uri::nrmname (name));
	}
      }
      throw Exception ("argument-error", 
		       "too many arguments with normalize-uri-name");
    } catch (...) {
      delete argv;
      throw;
    }
  }

  // normalize a uri name by prioritizing the system path

  Object* nwg_sysunm (Runnable* robj, Nameset* nset, Cons* args) {
    // evaluate the arguments
    Vector* argv = Vector::eval (robj, nset, args);
    long    argc = (argv == nilp) ? 0 : argv->length ();
    try {
      if (argc == 1) {
	String path = argv->getstring (0);
	delete argv; argv= nilp;
	return new String (Uri::sysname (path));
      }
      throw Exception ("argument-error", 
		       "too many arguments with system-uri-name");
    } catch (...) {
      delete argv;
      throw;
    }
  }
}
