// ---------------------------------------------------------------------------
// - Cart.cpp                                                                -
// - afnix:csm service - cloud object cart class 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-2013 amaury darsch                                   -
// ---------------------------------------------------------------------------

#include "Cart.hpp"
#include "System.hpp"
#include "Vector.hpp"
#include "Boolean.hpp"
#include "Integer.hpp"
#include "Runnable.hpp"
#include "QuarkZone.hpp"
#include "Exception.hpp"

namespace afnix {

  // -------------------------------------------------------------------------
  // - class section                                                         -
  // -------------------------------------------------------------------------

  // create a nil cart

  Cart::Cart (void) {
    reset ();
  }

  // create a cart with a rid

  Cart::Cart (const String& rid) {
    d_rid = rid;
    reset ();
  }

  // return the cart class name

  String Cart::repr (void) const {
    return "Cart";
  }

  // reset this cart
  
  void Cart::reset (void) {
    wrlock ();
    try {
      d_cos.reset ();
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // validate a rid by cart rid

  bool Cart::isrid (const String& rid) const {
    rdlock ();
    try {
      bool result = (d_rid == rid);
      unlock ();
      return result;
    } catch  (...) {
      unlock ();
      throw;
    }
  }

  // set the registration id

  void Cart::setrid (const String& rid) {
    wrlock ();
    try {
      d_rid = rid;
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }
  
  // get the registration id

  String Cart::getrid (void) const {
    rdlock ();
    try {
      String result = d_rid;
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // get the number of rco in the cart

  long Cart::length (void) const {
    rdlock ();
    try {
      long result = d_cos.length ();
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }
	
  // return true if the cart is empty

  bool Cart::empty (void) const {
    rdlock ();
    try {
      bool result = d_cos.empty ();
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // check if an rco exists in this cart

  bool Cart::exists (const t_long kid) const {
    rdlock ();
    try {
      // check the key id
      if (kid <= 0LL) {
	throw Exception ("cart-error", "invalid rco key id to validate");
      }
      // get the set length
      long slen = d_cos.length ();
      // loop in the set
      for (long i = 0; i < slen; i++) {
	Object* obj = d_cos.get (i);
	Rco*    rco = dynamic_cast <Rco*> (obj);
	if (rco == nilp) {
	  throw Exception ("internal-error", "invalid object in cart",
			   Object::repr (obj));
	}
	// check for valid key id
	if (rco->iskid (kid) == true) {
	  unlock ();
	  return true;
	}
      }
      unlock ();
      return false;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // get a rco at position

  Rco Cart::getat (const long idx) const {
    rdlock ();
    try {
      Rco* rco = dynamic_cast <Rco*> (d_cos.get (idx));
      if (rco == nilp) {
	throw Exception ("internal-error", "invalid object in cart");
      }
      Rco result = *rco;
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // add a rco in this cart

  t_long Cart::addrco (const Rco& rco) {
    wrlock ();
    try {
      // get the rco rid and validate
      String rid = rco.getrid ();
      if ((d_rid.isnil () == false) && (d_rid != rid)) {
	throw Exception ("cart-error", 
			 "invalid rid for registered cart", rid);
      }
      // get the rco key id and check
      t_long kid = rco.getkid ();
      if (kid <= 0LL) {
	// generate a unique id
	kid = System::uniqid ();
	// make sure the id is unique
	if (exists (kid) == true) {
	  throw Exception ("internal-error", "duplicate unique id found");
	}
	// create a copy of this rco with a key id
	Rco* co = new Rco (rco); co->setkid (kid);
	// add the object in the set
	d_cos.add (co);
      } else {
	// check if the rco exists
	if (exists (kid) == false) {
	  // create a copy of this rco with a key id
	  Rco* co = new Rco (rco);
	  // add the object in the set
	  d_cos.add (co);
	} else {
	  // find the rco in the set by index
	  long slen = d_cos.length ();
	  // loop in the set
	  for (long i = 0; i < slen; i++) {
	    Object* obj = d_cos.get (i);
	    Rco*     co = dynamic_cast <Rco*> (obj);
	    if (co == nilp) {
	      throw Exception ("internal-error", "invalid object in cart",
			       Object::repr (obj));
	    }
	    // check for valid key id
	    if (co->iskid (kid) == true) {
	      *co = rco;
	      break;
	    }
	  }
	}
      }
      unlock ();
      return kid;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // get a rco object by key id

  Rco Cart::getrco (const t_long kid) const {
    rdlock ();
    try {
      // check the key id
      if (kid <= 0LL) {
	throw Exception ("cart-error", "invalid rco key id to validate");
      }
      // get the set length
      long slen = d_cos.length ();
      // loop in the set
      for (long i = 0; i < slen; i++) {
	Object* obj = d_cos.get (i);
	Rco*    rco = dynamic_cast <Rco*> (obj);
	if (rco == nilp) {
	  throw Exception ("internal-error", "invalid object in cart",
			   Object::repr (obj));
	}
	// check for valid key id
	if (rco->iskid (kid) == true) {
	  Rco result = *rco;
	  unlock ();
	  return result;
	}
      }
      // not found
      throw Exception ("cart-error", "cannot find cart by id");
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // -------------------------------------------------------------------------
  // - object section                                                        -
  // -------------------------------------------------------------------------

  // the quark zone
  static const long QUARK_ZONE_LENGTH = 9;
  static QuarkZone  zone (QUARK_ZONE_LENGTH);

  // the object supported quarks
  static const long QUARK_GETAT   = zone.intern ("get-at");
  static const long QUARK_ADDRCO  = zone.intern ("add-rco");
  static const long QUARK_GETRCO  = zone.intern ("get-rco");
  static const long QUARK_LENGTH  = zone.intern ("length");
  static const long QUARK_ISRIDP  = zone.intern ("rid-p");
  static const long QUARK_SETRID  = zone.intern ("set-rid");
  static const long QUARK_GETRID  = zone.intern ("get-rid");
  static const long QUARK_EMPTYP  = zone.intern ("empty-p");
  static const long QUARK_EXISTSP = zone.intern ("exists-p");

  // create a new object in a generic way

  Object* Cart::mknew (Vector* argv) {
    long argc = (argv == nilp) ? 0 : argv->length ();
    // check for 0 argument
    if (argc == 0) return new Cart;
    // check for 1 argument
    if (argc == 1) {
      String rid = argv->getstring (0);
      return new Cart (rid);
    }
    throw Exception ("argument-error",
                     "too many argument with cart constructor");
  }

  // return true if the given quark is defined

  bool Cart::isquark (const long quark, const bool hflg) const {
    rdlock ();
    if (zone.exists (quark) == true) {
      unlock ();
      return true;
    }
    bool result = hflg ? Object::isquark (quark, hflg) : false;
    unlock ();
    return result;
  }
  
  // apply this object with a set of arguments and a quark
  
  Object* Cart::apply (Runnable* robj, Nameset* nset, const long quark,
		       Vector* argv) {
    // get the number of arguments
    long argc = (argv == nilp) ? 0 : argv->length ();
    
    // check for 0 argument
    if (quark == QUARK_EMPTYP) return new Boolean (empty  ());
    if (quark == QUARK_LENGTH) return new Integer (length ());
    if (quark == QUARK_GETRID) return new String  (getrid ());
    // check for 1 argument
    if (argc == 1) {
      if (quark == QUARK_ADDRCO) {
	Object* obj = argv->get (0);
	Rco*    rco = dynamic_cast <Rco*> (obj);
	if (rco == nilp) {
	  throw Exception ("type-error", "invalid object with cart add",
			   Object::repr (obj));
	}
	t_long result = addrco (*rco);
	return new Integer (result);
      }
      if (quark == QUARK_GETAT) {
	long idx = argv->getlong (0);
	return new Rco (getat (idx));
      }
      if (quark == QUARK_GETRCO) {
	t_long kid = argv->getlong (0);
	return new Rco (getrco (kid));
      }
      if (quark == QUARK_ISRIDP) {
	String rid = argv->getstring (0);
	return new Boolean (isrid (rid));
      }
      if (quark == QUARK_SETRID) {
	String rid = argv->getstring (0);
	setrid (rid);
	return nilp;
      }
      if (quark == QUARK_EXISTSP) {
	t_long kid = argv->getlong (0);
	return new Boolean (exists (kid));
      }
    }
    // call the object method
    return Object::apply (robj, nset, quark, argv);
  }
}
