// ---------------------------------------------------------------------------
// - Mixture.cpp                                                             -
// - afnix:tcz service - mixture 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-2023 amaury darsch                                   -
// ---------------------------------------------------------------------------

#include "Tczdb.hpp"
#include "Tczsid.hxx"
#include "Vector.hpp"
#include "Integer.hpp"
#include "Mixture.hpp"
#include "Evaluable.hpp"
#include "QuarkZone.hpp"
#include "Exception.hpp"
#include "AliasTable.hpp"

namespace afnix {

  // -------------------------------------------------------------------------
  // - private section                                                       -
  // -------------------------------------------------------------------------

  // mixture alias table
  static const long   AT_MIX_SIZE = 8L;
  static const String AT_MIX_DATA[AT_MIX_SIZE] =
    {
      PN_PRT_NAME, PN_MIX_NAME,
      PN_PRT_INFO, PN_MIX_INFO,
      PN_PRT_UUID, PN_MIX_UUID,
      PN_PRT_PLST, PN_MIX_PLST
    };
  
  // -------------------------------------------------------------------------
  // - class section                                                         -
  // -------------------------------------------------------------------------

  // create a default mixture

  Mixture::Mixture (void) {
    d_cmod = Tcz::CMOD_NONE;
    p_cdtm = nullptr;
  }
  
  // create an mixture by name

  Mixture::Mixture (const String& name) : Part (name) {
    d_cmod = Tcz::CMOD_NONE;
    p_cdtm = nullptr;
  }

  // create an mixture by name and info

  Mixture::Mixture (const String& name,
		    const String& info) : Part (name, info) {
    d_cmod = Tcz::CMOD_NONE;
    p_cdtm = nullptr;
  }
  
  // copy construct this mixture

  Mixture::Mixture (const Mixture& that) {
    that.rdlock ();
    try {
      // assign the base part
      Part::operator = (that);
      // copy locally
      d_cmod = that.d_cmod;
      Object::iref (p_cdtm = that.p_cdtm);
      that.unlock ();
    } catch (...) {
      that.unlock ();
      throw;
    }
  }
  
  // copy move this mixture

  Mixture::Mixture (Mixture&& that) noexcept {
    that.wrlock ();
    try {
      // move base part
      Part::operator = (static_cast<Part&&>(that));
      // copy locally
      d_cmod = that.d_cmod; that.d_cmod = Tcz::CMOD_NONE;
      p_cdtm = that.p_cdtm; that.p_cdtm = nullptr;
    } catch (...) {
      p_cdtm = nullptr;
    }
    that.unlock ();
  }

  // destroy this mixture

  Mixture::~Mixture (void) {
    Object::dref (p_cdtm);
  }
  
  // assign a mixture to this one

  Mixture& Mixture::operator = (const Mixture& that) {
    // check for self assignation
    if (this == &that) return *this;
    // lock and assign
    wrlock ();
    that.rdlock ();
    try {
      // assign base object
      Part::operator = (that);
      // assign locally
      d_cmod = that.d_cmod;
      Object::iref (that.p_cdtm); Object::dref (p_cdtm); p_cdtm = that.p_cdtm;
      unlock ();
      that.unlock ();
      return *this;
    } catch (...) {
      unlock ();
      that.unlock ();
      throw;
    }
  }
  
  // move a mixture to this one

  Mixture&
  Mixture::operator = (Mixture&& that) noexcept {
    // check for self assignation
    if (this == &that) return *this;
    // lock and assign
    wrlock ();
    that.wrlock ();
    try {
      // assign base object
      Part::operator = (static_cast<Part&&>(that));
      // move locally
      d_cmod = that.d_cmod; that.d_cmod = Tcz::CMOD_NONE;
      p_cdtm = that.p_cdtm; that.p_cdtm = nullptr;
    } catch (...) {
      p_cdtm = nullptr;
    }
    unlock ();
    that.unlock ();
    return *this;
  }
  
  // return the mixture class name
  
  String Mixture::repr (void) const {
    return "Mixture";
  }
  
  // return a clone of this object
  
  Object* Mixture::clone (void) const {
    return new Mixture (*this);
  }
  
  // return the serial did

  t_word Mixture::getdid (void) const {
    return SRL_DEOD_TCZ;
  }

  // return the serial sid
  
  t_word Mixture::getsid (void) const {
    return SRL_MIXT_SID;
  }

  // serialize this mixture

  void Mixture::wrstream (OutputStream& os) const {
    rdlock ();
    try {
      // serialize base object
      Part::wrstream (os);
      // serialize locally
      Serial::wrbyte (d_cmod, os);
      if (p_cdtm == nullptr) {
	Serial::wrnilid (os);
      } else {
	p_cdtm->serialize (os);
      }
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // deserialize this mixture

  void Mixture::rdstream (InputStream& is) {
    wrlock ();
    try {
      // deserialize base object
      Part::rdstream (is);
      // deserialize locally
      d_cmod = static_cast<Tcz::t_cmod>(Serial::rdbyte (is));
      p_cdtm = dynamic_cast<Collection*>(Serial::deserialize (is));
      Object::iref (p_cdtm);
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // get the mixture plist

  Plist Mixture::getplst (void) const {
    // the alias table
    static const AliasTable atbl (AT_MIX_SIZE, AT_MIX_DATA);
    rdlock ();
    try {
      // get the base plist
      Plist result = atbl.map (Part::getplst ());
      // add the mixture length
      long rlen = length ();
      result.add (PN_MIX_CMOD, PI_MIX_CMOD, Tcz::tostring(d_cmod));
      result.add (PN_MIX_LGTH, PI_MIX_LGTH, (t_long) rlen);
      // collect datum info
      for (long k = 0L; k < rlen; k++) {
	// get the datum
	Datum* dtum = get(k);
	if (dtum == nullptr) continue;
	// collect plist and merge
	Plist dlst = dtum->getplst ();
	result = result.merge (dlst, k);
      }
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // get the mixture object view

  HashTable Mixture::toview (void) const {
    // the alias table
    static const AliasTable atbl (AT_MIX_SIZE, AT_MIX_DATA);
    rdlock ();
    try {
      // get the base plist
      HashTable result = atbl.map (Part::toview ());
      // create a datum vector
      Vector* data = new Vector;
      // loop in the datum collection
      long rlen = length ();
      for (long k = 0L; k < rlen; k++) {
	// get the datum
	Datum* dtum = get(k);
	if (dtum == nullptr) continue;
	// collect view and add and merge
	HashTable htbl = dtum->toview ();
	data->add (new HashTable (htbl));
      }
      result.add (PN_MIX_DATA, data);
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }
  
  // get a subpart by name

  Part* Mixture::subpart (const String& name) const {
    rdlock ();
    try {
      // check the collection
      Part* result = (p_cdtm == nullptr) ? nullptr : p_cdtm->subpart (name);
      // check the part
      if (result == nullptr) result = Part::subpart (name);
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // set the mixture content mode

  void Mixture::setcmod (const Tcz::t_cmod cmod) {
    wrlock ();
    try {
      d_cmod = cmod;
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }
  
  // get the mixture content mode

  Tcz::t_cmod Mixture::getcmod (void) const {
    rdlock ();
    try {
      Tcz::t_cmod result = d_cmod;
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }
  
  // get the number of datum

  long Mixture::length (void) const {
    rdlock ();
    try {
      long result = (p_cdtm == nullptr) ? 0L : p_cdtm->length ();
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // add a datum to the collection

  void Mixture::add (Datum* dtum) {
    // check for nil first
    if (dtum == nullptr) return;
    // lock and add
    wrlock ();
    try {
      if (p_cdtm == nullptr) Object::iref (p_cdtm = new Collection);
      p_cdtm->addpart (dtum);
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // get a datum by index

  Datum* Mixture::get (const long didx) const {
    rdlock ();
    try {
      // get the part index
      Part* part = (p_cdtm == nullptr) ? nullptr : p_cdtm->getat (didx);
      // map a datum
      auto result = dynamic_cast<Datum*>(part);
      // here it is
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // get a datum by name
  
  Datum* Mixture::find (const String& name) const {
    rdlock ();
    try {
      // get the collection length
      long clen = (p_cdtm == nullptr) ? 0L : p_cdtm->length ();
      // loop in the collection
      for (long k = 0L; k < clen; k++) {
	// get the part by index
	Part* part = (p_cdtm == nullptr) ? nullptr : p_cdtm->getat (k);
	// map a datum
	auto dtum = dynamic_cast<Datum*>(part);
	if (dtum == nullptr) continue;
	// check by datum name
	if (dtum->getname () == name) {
	  unlock ();
	  return dtum;
	}
	// check by datum kid
	if (dtum->getkid().tostring() == name) {
	  unlock ();
	  return dtum;
	}
      }
      // nothing found
      unlock ();
      return nullptr;
    } catch (...) {
      unlock ();
      throw;
    }
  }
  
  // -------------------------------------------------------------------------
  // - object section                                                        -
  // -------------------------------------------------------------------------

  // the quark zone
  static const long QUARK_ZONE_LENGTH = 6;
  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_FIND    = zone.intern ("find");
  static const long QUARK_LENGTH  = zone.intern ("length");
  static const long QUARK_SETCMOD = zone.intern ("set-content-mode");
  static const long QUARK_GETCMOD = zone.intern ("get-content-mode");

  // create a new object in a generic way

  Object* Mixture::mknew (Vector* argv) {
    long argc = (argv == nullptr) ? 0 : argv->length ();
    // create a default mixture
    if (argc == 0) return new Mixture;
    // check for 1 argument
    if (argc == 1) {
      String name = argv->getstring (0);
      return new Mixture (name);
    }
    // check for 2 arguments
    if (argc == 2) {
      String name = argv->getstring (0);
      String info = argv->getstring (1);
      return new Mixture (name, info);
    }
    throw Exception ("argument-error",
                     "too many argument with mixture constructor");
  }

  // return true if the given quark is defined

  bool Mixture::isquark (const long quark, const bool hflg) const {
    rdlock ();
    try {
      if (zone.exists (quark) == true) {
	unlock ();
	return true;
      }
      bool result = hflg ? Part::isquark (quark, hflg) : false;
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }
  
  // apply this object with a set of arguments and a quark
  
  Object* Mixture::apply (Evaluable* zobj, Nameset* nset, const long quark,
			  Vector* argv) {
    // get the number of arguments
    long argc = (argv == nullptr) ? 0 : argv->length ();

    // check for 0 argument
    if (argc == 0) {
      if (quark == QUARK_LENGTH) return new Integer (length ());
      if (quark == QUARK_GETCMOD) return Tcz::toitem (getcmod ());
    }
    // check for 1 argument
    if (argc == 1) {
      if (quark == QUARK_ADD) {
	Object* obj = argv->get (0);
	// check for a part
	auto part = dynamic_cast <Datum*> (obj);
        if (part == nullptr) {
	  throw Exception ("type-error", "invalid object for add",
			   Object::repr (obj));
	}
	add (part);
	return nullptr;
      }
      if (quark == QUARK_GET) {
	rdlock ();
	try {
	  long didx = argv->getlong (0);
	  Object* result = get (didx);
	  zobj->post (result);
	  unlock ();
	  return result;
	} catch (...) {
	  unlock ();
	  throw;
	}
      }
      if (quark == QUARK_FIND) {
	rdlock ();
	try {
	  String name = argv->getstring (0);
	  Object* result = find (name);
	  zobj->post (result);
	  unlock ();
	  return result;
	} catch (...) {
	  unlock ();
	  throw;
	}
      }
      if (quark == QUARK_SETCMOD) {
	Object* obj = argv->get (0);
	Item* item = dynamic_cast <Item*> (obj);
        if (item == nullptr) {
	  throw Exception ("argument-error", "invalid object as mixure mode",
			   Object::repr (obj));
	}
	Tcz::t_cmod cmod = Tcz::tocmod (*item);
	setcmod (cmod);
	return nullptr;
      }
    }
    // call the part method
    return Part::apply (zobj, nset, quark, argv);
  }
}
