// ---------------------------------------------------------------------------
// - Set.cpp                                                                 -
// - standard object library - set 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 "Set.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 set

  Set::Set (void) {
    d_size = 0;
    d_slen = 0;
    p_vset = nilp;
  }

  // create a new set with an object

  Set::Set (Object* obj) {
    d_size = 0;
    d_slen = 0;
    p_vset = nilp;
    add (obj);
  }

  // destroy this set

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

  // return the class name
  String Set::repr (void) const {
    return "Set";
  }

  // return the set serial code

  t_byte Set::serialid (void) const {
    return SERIAL_OSET_ID;
  }

  // serialize this set

  void Set::wrstream (OutputStream& os) const {
    rdlock ();
    try {
      // write the set size
      Integer size (d_slen);
      size.wrstream (os);
      // write the objects
      for (long i = 0; i < d_slen; i++) {
	Object* obj = p_vset[i];
	if (obj == nilp) {
	  throw Exception ("serialize-error", 
			   "invalid nil object for set serialization");
	}
	// get the object serial form
	Serial* sobj = dynamic_cast <Serial*> (obj);
	if (sobj == nilp) {
	  throw Exception ("serial-error", "cannot serialize object", 
			   obj->repr ());
	}
	sobj->serialize (os);
      }
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // deserialize this set

  void Set::rdstream (InputStream& is) {
    wrlock ();
    try {
      reset ();
      // get the vector length
      Integer slen;
      slen.rdstream (is);
      long size = slen.tolong ();
      // read in each object
      for (long i = 0; i < size; i++) add (Serial::deserialize (is));
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // reset this set

  void Set::reset (void) {
    wrlock ();
    try {
      for (long i = 0; i < d_slen; i++) Object::dref (p_vset[i]);
      delete [] p_vset;
      d_size = 0;
      d_slen = 0;
      p_vset = nilp;
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // return the size of this set

  long Set::length (void) const {
    rdlock ();
    try {
      long result = d_slen;
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // get an object by index

  Object* Set::get (const long index) const {
    rdlock ();
    try {
      if ((index < 0)|| (index >= d_slen)) {
	throw Exception ("index-error", "illegal index in set access");
      }
      Object* result = p_vset[index];
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // check if an object exists

  bool Set::exists (Object* obj) const {
    if (obj == nilp) return false;
    rdlock ();
    try {
      for (long i = 0; i < d_slen; i++) {
	if (p_vset[i] == obj) {
	  unlock ();
	  return true;
	}
      }
      unlock ();
      return false;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // add an object to this set

  void Set::add (Object* obj) {
    if (obj == nilp) return;
    wrlock ();
    try {
      // check that the object is not already there
      if (exists (obj) == false) {
	// do we need to resize
	if (d_slen == d_size) resize (d_slen*2);
	// add the object
	Object::iref (p_vset[d_slen++]= obj);
      }
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // remove an object from this set

  bool Set::remove (Object* obj) {
    // do not take the nil object
    if (obj == nilp) return false;
    wrlock ();
    bool pack = false;
    for (long i = 0; i < d_slen; i++) {
      if (pack == false) {
	if (p_vset[i] == obj) {
	  Object::dref (obj);
	  p_vset[i] = nilp;
	  pack = true;
	}
      } else {
	p_vset[i-1] = p_vset[i];
	p_vset[i] = nilp;
      }
    }
    if (pack == true) d_slen--;
    unlock ();
    return pack;
  }
  
  // merge a set into this one

  void Set::merge (const Set& cset) {
    wrlock      ();
    cset.rdlock ();
    try {
      if (cset.p_vset != nilp) {
	for (long i = 0; i < cset.d_slen; i++) {
	  Object* obj = cset.p_vset[i];
	  add (obj);
	}
      }      
      cset.unlock ();
      unlock      ();
    } catch (...) {
      cset.unlock ();
      unlock      ();
      throw;
    }
  }
  // remix this set with a certain number of passes

  void Set::remix (const long num) {
    if (num <= 0) return;
    wrlock ();
    // check for null size
    if (d_slen == 0) {
      unlock ();
      return;
    }
    // resize the set to its cardinal
    resize (d_slen);
    // loop for remix
    for (long i = 0; i < num; i++) {
      for (long j = 0; j < d_slen; j++) {
	// get random indexes
	long x = Utility::longrnd (d_slen-1);
	long y = Utility::longrnd (d_slen-1);
	// check indexes
	if ((x < 0) || (x >= d_slen)) x = j;
	if ((y < 0) || (y >= d_slen)) y = j;
	if (x == y) continue;
	// swap the object
	Object* obj = p_vset[x];
	p_vset[x] = p_vset[y];
	p_vset[y] = obj;
      }
    }
    unlock ();
  }

  // get a random subset by size

  Set* Set::getrss (const long size) const {
    rdlock ();
    try {
      Set* result = new Set;
      if (p_vset != nilp) {
	for (long i = 0; i < size; i++) {
	  long index = Utility::longrnd (d_slen-1);
	  if ((index < 0) || (index >= d_slen)) continue;
	  result->add (p_vset[index]);
	}
      }
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // resize this set

  void Set::resize (const long size) {
    wrlock ();
    try {
      // check for valid size
      if (size < d_slen) {
	unlock ();
	return;
      }
      // process 0 case first
      if (size == 0) {
	d_size = 1;
	p_vset = new Object*[d_size];
	p_vset[0] = nilp;
	unlock ();
	return;
      }
      // prepare new vector
      Object** vset = new Object*[size];
      for (long i = 0; i < d_slen; i++) vset[i] = p_vset[i];
      for (long i = d_slen; i < size; i++) vset[i] = nilp;
      // clean old and restore
      delete [] p_vset;
      d_size = size;
      p_vset = vset;
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // return a set iterator

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

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

  // the object supported quarks
  static const long QUARK_ADD    = zone.intern ("add");
  static const long QUARK_GET    = zone.intern ("get");
  static const long QUARK_RESET  = zone.intern ("reset");
  static const long QUARK_MERGE  = zone.intern ("merge");
  static const long QUARK_REMIX  = zone.intern ("remix");
  static const long QUARK_LENGTH = zone.intern ("length");
  static const long QUARK_EXISTP = zone.intern ("exists-p");
  static const long QUARK_REMOVE = zone.intern ("remove");
  static const long QUARK_GETRSS = zone.intern ("get-random-subset");

  // create a new object in a generic way

  Object* Set::mknew (Vector* argv) {
    // create the set
    Set* result = new Set;
    // get the objects
    long argc = (argv == nilp) ? 0 : argv->length ();
    for (long i = 0; i < argc; i++) result->add (argv->get (i));
    return result;
  }

  // return true if the given quark is defined

  bool Set::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* Set::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_LENGTH) return new Integer (length ());
      if (quark == QUARK_RESET) {
	reset ();
	return nilp;
      }
    }
    
    // dispatch 1 argument
    if (argc == 1) {
      if (quark == QUARK_ADD) {
	Object* result = argv->get (0);
	add (result);
	robj->post (result);
	return result;
      }
      if (quark == QUARK_EXISTP) {
	Object* obj = argv->get (0);
	return new Boolean (exists (obj));
      }
      if (quark == QUARK_GET) {
	long index = argv->getlong (0);
	rdlock();
	try {
	  Object* result = get (index);
	  robj->post (result);
	  unlock ();	    
	  return result;
	} catch (...) {
	  unlock ();
	  throw;
	}
      }
      if (quark == QUARK_MERGE) {
	Object* obj = argv->get (0);
	Set* cset = dynamic_cast<Set*> (obj);
	if (cset == nilp) {
	  throw Exception ("type-error", "invalid object with merge",
			   Object::repr (obj));
	}
	merge (*cset);
	return nilp;
      }
      if (quark == QUARK_REMIX) {
	long num = argv->getlong (0);
	remix (num);
	return nilp;
      }
      if (quark == QUARK_REMOVE) {
	Object* obj = argv->get (0);
	bool result = remove (obj);
	return new Boolean (result);
      }
      if (quark == QUARK_GETRSS) {
	long size = argv->getlong (0);
	return getrss (size);
      }
    }
    // 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

  Setit::Setit (Set* set) {
    Object::iref (p_set = set);
    d_idx = 0;
    begin ();
  }

  // destroy this set iterator

  Setit::~Setit (void) {
    Object::dref (p_set);
  }

  // return the class name

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

  // reset the iterator to the begining

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

  // reset the iterator to the end

  void Setit::end (void) {
    wrlock ();
    if (p_set != nilp) p_set->rdlock ();
    try {
      if (p_set != nilp) {
	d_idx = (p_set->d_slen == 0) ? 0 : p_set->d_slen - 1;
      } else {
	d_idx = 0;
      }
      if (p_set != nilp) p_set->unlock ();
      unlock ();
    } catch (...) {
      if (p_set != nilp) p_set->unlock ();
      unlock ();
      throw;
    }
  }

  // go to the next object

  void Setit::next (void) {
    wrlock ();
    if (p_set != nilp) p_set->rdlock ();
    try {
      if (p_set != nilp) {
	if (++d_idx >= p_set->d_slen) d_idx = p_set->d_slen;
      } else {
	d_idx = 0;
      }
      if (p_set != nilp) p_set->unlock ();
      unlock ();
    } catch (...) {
      if (p_set != nilp) p_set->unlock ();
      unlock ();
      throw;
    }
  }

  // go to the previous object
  void Setit::prev (void) {
    wrlock ();
    try {
      if (--d_idx < 0) d_idx = 0;
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // get the object at the current position

  Object* Setit::getobj (void) const {
    rdlock ();
    if (p_set != nilp) p_set->rdlock ();
    try {
      Object* result = nilp;
      if ((p_set != nilp) && (d_idx < p_set->d_slen)) {
	result = p_set->get (d_idx);
      }
      if (p_set != nilp) p_set->unlock ();
      unlock ();
      return result;
    } catch (...) {
      if (p_set != nilp) p_set->unlock ();
      unlock ();
      throw;
    }
  }

  // return true if the iterator is at the end

  bool Setit::isend (void) {
    rdlock ();
    if (p_set != nilp) p_set->rdlock ();
    try {
      bool result = false;
      if (p_set != nilp) {
	result = (d_idx >= p_set->d_slen);
      }
      if (p_set != nilp) p_set->unlock ();
      unlock ();
      return result;
    } catch (...) {
      if (p_set != nilp) p_set->unlock ();
      unlock ();
      throw;
    }
  }
}
