// ---------------------------------------------------------------------------
// - Plist.cpp                                                               -
// - standard object library - property list 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-2011 amaury darsch                                   -
// ---------------------------------------------------------------------------

#include "Plist.hpp"
#include "Stdsid.hxx"
#include "Vector.hpp"
#include "Utility.hpp"
#include "Integer.hpp"
#include "Boolean.hpp"
#include "Runnable.hpp"
#include "QuarkZone.hpp"
#include "Exception.hpp"
#include "InputStream.hpp"
#include "OutputStream.hpp"

namespace afnix {

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

  // create a new empty plist

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

  // copy construct this plist

  Plist::Plist (const Plist& that) {
    reset ();
    that.rdlock ();
    try {
      long plen = that.length ();
      for (long i = 0; i < plen; i++) {
	Property* prop = that.get (i);
	if (prop == nilp) continue;
	add (new Property (*prop));
      }
      that.unlock ();
    } catch (...) {
      that.unlock ();
      throw;
    }
  }

  // destroy this set

  Plist::~Plist (void) {
    reset ();
  }

  // return the class name

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

  // return a clone of this object

  Object* Plist::clone (void) const {
    return new Plist (*this);
  }

  // return the plist serial code

  t_byte Plist::serialid (void) const {
    return SERIAL_PLST_ID;
  }

  // serialize this plist

  void Plist::wrstream (OutputStream& os) const {
    rdlock ();
    try {
      d_plist.wrstream (os);
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // deserialize this plist

  void Plist::rdstream (InputStream& is) {
    wrlock ();
    try {
      // reset and read the vector
      reset  ();
      d_plist.rdstream (is);
      // update the hash table
      long len = d_plist.length ();
      for (long i = 0; i < len; i++) {
	Property* prop = dynamic_cast <Property*> (d_plist.get (i));
	if (prop == nilp) {
	  throw Exception ("internal-error", 
			   "invalid nil property whie deserializing");
	}
	String name = prop->getname ();
	d_phash.add (name, prop);
      }
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  //  assign a plist to this one

  Plist& Plist::operator = (const Plist& that) {
    // check for equality
    if (this == &that) return *this;
    // lock and copy
    wrlock ();
    that.rdlock ();
    try {
      // reset the current list
      reset ();
      // copy the new one
      long plen = that.length ();
      for (long i = 0; i < plen; i++) {
	Property* prop = that.get (i);
	if (prop == nilp) continue;
	add (new Property (*prop));
      }
      // unlock and done
      that.unlock ();
      unlock ();
      return *this;
    } catch (...) {
      that.unlock ();
      unlock ();
      throw;
    }
  }

  // reset this plist

  void Plist::reset (void) {
    wrlock ();
    d_plist.reset ();
    d_phash.reset ();
    unlock ();
  }

  // return true if the list is empty

  bool Plist::empty (void) const {
    rdlock ();
    bool result = d_plist.empty ();
    unlock ();
    return result;
  }

  // return the length of this plist

  long Plist::length (void) const {
    rdlock ();
    long result = d_plist.length ();
    unlock ();
    return result;
  }

  // get a property object by index

  Property* Plist::get (const long index) const {
    rdlock ();
    try {
      Property* result = dynamic_cast <Property*> (d_plist.get (index));
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // get a property by name

  Property* Plist::find (const String& name) const {
    rdlock ();
    try {
      Property* result = dynamic_cast <Property*> (d_phash.get (name));
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // return true if a property exists by name

  bool Plist::exists (const String& name) const {
    rdlock ();
    bool result = d_phash.exists (name);
    unlock ();
    return result;
  }

  // return true if a property exists by name with a certain value

  bool Plist::exists (const String& name, const Literal& lval) const {
    rdlock ();
    try {
      if (d_phash.exists (name) == false) {
	unlock ();
	return false;
      }
      // get the property value
      String pval = getpval (name);
      bool result = (pval == lval.tostring ());
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // add a property to this plist

  void Plist::add (Property* prop) {
    if (prop == nilp) return;
    wrlock ();
    try {
      // get the propery name
      String name = prop->getname ();
      // check if the property alreay exists
      if (exists (name) == true) {
	unlock ();
	throw Exception ("plist-error", "propety already exists", name);
      }
      // add the property in the list
      d_plist.add (prop);
      // add the property in the hash
      d_phash.add (name, prop);
      // done
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // add a property by name and boolean value

  void Plist::add (const String& name, const bool bval) {
    wrlock ();
    Property* prop = new Property (name, bval);
    try {
      add (prop);
      unlock ();
    } catch (...) {
      delete prop;
      unlock ();
      throw;
    }
  }

  // add a property by name and integer value

  void Plist::add (const String& name, const t_long ival) {
    wrlock ();
    Property* prop = new Property (name, ival);
    try {
      add (prop);
      unlock ();
    } catch (...) {
      delete prop;
      unlock ();
      throw;
    }
  }

  // add a property by name and real value

  void Plist::add (const String& name, const t_real rval) {
    wrlock ();
    Property* prop = new Property (name, rval);
    try {
      add (prop);
      unlock ();
    } catch (...) {
      delete prop;
      unlock ();
      throw;
    }
  }

  // add a property by name and value

  void Plist::add (const String& name, const Literal& lval) {
    wrlock ();
    Property* prop = new Property (name, lval);
    try {
      add (prop);
      unlock ();
    } catch (...) {
      delete prop;
      unlock ();
      throw;
    }
  }

  // add a property by name, info and boolean value

  void Plist::add (const String& name, const String& info, const bool bval) {
    wrlock ();
    Property* prop = new Property (name, info, bval);
    try {
      add (prop);
      unlock ();
    } catch (...) {
      delete prop;
      unlock ();
      throw;
    }
  }

  // add a property by name, info and integer value

  void Plist::add (const String& name, const String& info, 
		   const t_long  ival) {
    wrlock ();
    Property* prop = new Property (name, info, ival);
    try {
      add (prop);
      unlock ();
    } catch (...) {
      delete prop;
      unlock ();
      throw;
    }
  }

  // add a property by name, info and real value

  void Plist::add (const String& name, const String& info,
		   const t_real  rval) {
    wrlock ();
    Property* prop = new Property (name, info, rval);
    try {
      add (prop);
      unlock ();
    } catch (...) {
      delete prop;
      unlock ();
      throw;
    }
  }

  // add a property by name, info and value

  void Plist::add (const String&  name, const String& info,
		   const Literal& lval) {
    wrlock ();
    Property* prop = new Property (name, info, lval);
    try {
      add (prop);
      unlock ();
    } catch (...) {
      delete prop;
      unlock ();
      throw;
    }
  }

  // get a property by name or throw an exception

  Property* Plist::lookup (const String& name) const {
    rdlock ();
    try {
      Property* result = dynamic_cast <Property*> (d_phash.lookup (name));
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // get a property value by name

  String Plist::getpval (const String& name) const {
    rdlock ();
    try {
      // get the property
      Property* prop = lookup (name);
      // map the value
      String result = prop->getpval ();
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // map a property to a boolean value

  bool Plist::tobool (const String& name) const {
    rdlock ();
    try {
      // get the property
      Property* prop = lookup (name);
      // map to a boolean value
      bool result = prop->tobool ();
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // map a property to an integer value

  t_long Plist::tolong (const String& name) const {
    rdlock ();
    try {
      // get the property
      Property* prop = lookup (name);
      // map to an integer  value
      t_long result = prop->tolong ();
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // map a property to a real value

  t_real Plist::toreal (const String& name) const {
    rdlock ();
    try {
      // get the property
      Property* prop = lookup (name);
      // map to an integer  value
      t_real result = prop->toreal ();
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // set a property by name and boolean value

  void Plist::set (const String& name, const bool bval) {
    wrlock ();
    try {
      if (exists (name) == true) {
	Property* prop = lookup (name);
	prop->setpval (bval);
      } else {
	add (name, bval);
      }
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // set a property by name and integer value

  void Plist::set (const String& name, const t_long ival) {
    wrlock ();
    try {
      if (exists (name) == true) {
	Property* prop = lookup (name);
	prop->setpval (ival);
      } else {
	add (name, ival);
      }
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // set a property by name and real value

  void Plist::set (const String& name, const t_real rval) {
    wrlock ();
    try {
      if (exists (name) == true) {
	Property* prop = lookup (name);
	prop->setpval (rval);
      } else {
	add (name, rval);
      }
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // set a property by name and value

  void Plist::set (const String& name, const Literal& lval) {
    wrlock ();
    try {
      if (exists (name) == true) {
	Property* prop = lookup (name);
	prop->setpval (lval);
      } else {
	add (name, lval);
      }
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // return a plist iterator

  Iterator* Plist::makeit (void) {
    rdlock ();
    try {
      Iterator* result = new Plistit (this);
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }
  
  // -------------------------------------------------------------------------
  // - object section                                                        -
  // -------------------------------------------------------------------------

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

  // the object supported quarks
  static const long QUARK_ADD     = zone.intern ("add");
  static const long QUARK_SET     = zone.intern ("set");
  static const long QUARK_GET     = zone.intern ("get");
  static const long QUARK_FIND    = zone.intern ("find");
  static const long QUARK_RESET   = zone.intern ("reset");
  static const long QUARK_LENGTH  = zone.intern ("length");
  static const long QUARK_LOOKUP  = zone.intern ("lookup");
  static const long QUARK_EMPTYP  = zone.intern ("empty-p");
  static const long QUARK_EXISTP  = zone.intern ("exists-p");
  static const long QUARK_GETPVAL = zone.intern ("get-value");

  // create a new object in a generic way

  Object* Plist::mknew (Vector* argv) {
    // get the number of arguments
    long argc = (argv == nilp) ? 0 : argv->length ();

    // check for 0 argument
    if (argc == 0) return new Plist;
    // too many arguments
    throw Exception ("argument-error", 
		     "too many argument with plist constructor");
  }

  // return true if the given quark is defined

  bool Plist::isquark (const long quark, const bool hflg) const {
    rdlock ();
    if (zone.exists (quark) == true) {
      unlock ();
      return true;
    }
    bool result = hflg ? Iterable::isquark (quark, hflg) : false;
    if (result == false) {
      result = hflg ? Serial::isquark (quark, hflg) : false;
    }
    unlock ();
    return result;
  }
  
  // apply this object with a set of arguments and a quark

  Object* Plist::apply (Runnable* robj, Nameset* nset, const long quark,
			Vector* argv) {
    // get the number of arguments
    long argc = (argv == nilp) ? 0 : argv->length ();
    
    // dispatch 0 argument
    if (argc == 0) {
      if (quark == QUARK_EMPTYP) return new Boolean (empty  ());
      if (quark == QUARK_LENGTH) return new Integer (length ());
      if (quark == QUARK_RESET) {
	reset ();
	return nilp;
      }
    }
    
    // dispatch 1 argument
    if (argc == 1) {
      if (quark == QUARK_ADD) {
	Object* obj = argv->get (0);
	Property* prop = dynamic_cast <Property*> (obj);
	if ((obj != nilp) && (prop == nilp)) {
	  throw Exception ("type-error", "invalid object with add",
			   Object::repr (obj));
	}
	add (prop);
	return nilp;
      }
      if (quark == QUARK_FIND) {
	rdlock ();
	try {
	  String name = argv->getstring (0);
	  Object* result = find (name);
	  robj->post (result);
	  unlock ();
	  return result;
	} catch (...) {
	  unlock ();
	  throw;
	}
      }
      if (quark == QUARK_LOOKUP) {
	rdlock ();
	try {
	  String name = argv->getstring (0);
	  Object* result = lookup (name);
	  robj->post (result);
	  unlock ();
	  return result;
	} catch (...) {
	  unlock ();
	  throw;
	}
      }
      if (quark == QUARK_EXISTP) {
	String name = argv->getstring (0);
	return new Boolean (exists (name));
      }
      if (quark == QUARK_GETPVAL) {
	String name = argv->getstring (0);
	return new String (getpval (name));
      }
      if (quark == QUARK_GET) {
	long index = argv->getlong (0);
	rdlock();
	try {
	  Object* result = get (index);
	  robj->post (result);
	  unlock ();	    
	  return result;
	} catch (...) {
	  unlock ();
	  throw;
	}
      }
    }

    // dispatch 2 arguments
    if (argc == 2) {
      if (quark == QUARK_EXISTP) {
	String   name = argv->getstring (0);
	Object*   obj = argv->get (1);
	Literal* lobj = dynamic_cast <Literal*> (obj);
	if (lobj == nilp) {
	throw Exception ("type-error", "invalid object with exists",
			 Object::repr (obj));
	}
	return new Boolean (exists (name, *lobj));
      }
      if (quark == QUARK_ADD) {
	String   name = argv->getstring (0);
	Object*   obj = argv->get (1);
	Literal* lobj = dynamic_cast <Literal*> (obj);
	if (lobj == nilp) {
	throw Exception ("type-error", "invalid object with add",
			 Object::repr (obj));
	}
	add (name, *lobj);
	return nilp;
      }
      if (quark == QUARK_SET) {
	String   name = argv->getstring (0);
	Object*   obj = argv->get (1);
	Literal* lobj = dynamic_cast <Literal*> (obj);
	if (lobj == nilp) {
	throw Exception ("type-error", "invalid object with set",
			 Object::repr (obj));
	}
	set (name, *lobj);
	return nilp;
      }
    }
    // dispatch 3 arguments
    if (argc == 3) {
      if (quark == QUARK_ADD) {
	String   name = argv->getstring (0);
	String   info = argv->getstring (1);
	Object*   obj = argv->get (2);
	Literal* lobj = dynamic_cast <Literal*> (obj);
	if (lobj == nilp) {
	throw Exception ("type-error", "invalid object with add",
			 Object::repr (obj));
	}
	add (name, info, *lobj);
	return nilp;
      }
    }
    // check the iterable method
    if (Iterable::isquark (quark, true) == true) {
      return Iterable::apply (robj, nset, quark, argv);
    }
    // call the serial method
    return Serial::apply (robj, nset, quark, argv);
  }

  // -------------------------------------------------------------------------
  // - iterator section                                                      -
  // -------------------------------------------------------------------------

  // create a new set iterator

  Plistit::Plistit (Plist* plst) {
    Object::iref (p_plst = plst);
    d_pidx = 0;
    begin ();
  }

  // destroy this set iterator

  Plistit::~Plistit (void) {
    Object::dref (p_plst);
  }

  // return the class name

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

  // reset the iterator to the begining

  void Plistit::begin (void) {
    wrlock ();
    try {
      d_pidx = 0;
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // reset the iterator to the end

  void Plistit::end (void) {
    wrlock ();
    if (p_plst != nilp) p_plst->rdlock ();
    try {
      if (p_plst != nilp) {
	long plen = p_plst->length ();
	d_pidx = (plen == 0) ? 0 : plen - 1;
      } else {
	d_pidx = 0;
      }
      if (p_plst != nilp) p_plst->unlock ();    
      unlock ();
    } catch (...) {
      if (p_plst != nilp) p_plst->unlock ();    
      unlock ();
      throw;
    }
  }

  // go to the next object

  void Plistit::next (void) {
    wrlock ();
    if (p_plst != nilp) p_plst->rdlock ();
    try {
      if (p_plst != nilp) {
	long plen = p_plst->length ();      
	if (++d_pidx >= plen) d_pidx = plen;
      } else {
	d_pidx = 0;
      }
      if (p_plst != nilp) p_plst->unlock ();    
      unlock ();
    } catch (...) {
      if (p_plst != nilp) p_plst->unlock ();    
      unlock ();
      throw;
    }
  }

  // go to the previous object

  void Plistit::prev (void) {
    wrlock ();
    try {
      if (--d_pidx < 0) d_pidx = 0;
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // get the object at the current position

  Object* Plistit::getobj (void) const {
    rdlock ();
    if (p_plst != nilp) p_plst->rdlock ();
    try {
      Object* result = nilp;
      long plen = p_plst->length ();            
      if ((p_plst != nilp) && (d_pidx < plen)) {
	result = p_plst->get (d_pidx);
      }
      if (p_plst != nilp) p_plst->unlock ();    
      unlock ();
      return result;
    } catch (...) {
      if (p_plst != nilp) p_plst->unlock ();    
      unlock ();
      throw;
    }
  }

  // return true if the iterator is at the end

  bool Plistit::isend (void) {
    rdlock ();
    if (p_plst != nilp) p_plst->rdlock ();
    try {
      bool result = false;
      if (p_plst != nilp) {
	long plen = p_plst->length ();            
	result = (d_pidx >= plen);
      }
      if (p_plst != nilp) p_plst->unlock ();    
      unlock ();
      return result;
    } catch (...) {
      if (p_plst != nilp) p_plst->unlock ();    
      unlock ();
      throw;
    }
  }
}
