// ---------------------------------------------------------------------------
// - Queue.cpp                                                               -
// - standard object library - queue 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 "Queue.hpp"
#include "Vector.hpp"
#include "Integer.hpp"
#include "Boolean.hpp"
#include "Evaluable.hpp"
#include "QuarkZone.hpp"
#include "Exception.hpp"
#include "fifo.tcc"

namespace afnix {

  // -------------------------------------------------------------------------
  // - class section                                                         -
  // -------------------------------------------------------------------------
  
  // create a new queue
  
  Queue::Queue (void) {
    p_fifo = new t_fifo<Object*>;
  }
  
  // create a new queue by size
  
  Queue::Queue (const long size) {
    p_fifo = new t_fifo<Object*>(size);
  }

  // copy construct this queue
  
  Queue::Queue (const Queue& that) {
    that.rdlock ();
    try {
      // allocate the queue
      p_fifo = new t_fifo<Object*>;
      // copy by getter
      long flen = that.p_fifo->length (); p_fifo->resize (flen);
      for (long k = 0L; k < flen; k++) {
	p_fifo->push (Object::iref (that.p_fifo->get(k)));
      }
      that.unlock ();
    } catch (...) {
      that.unlock ();
      throw;
    }
  }

  // destroy this queue

  Queue::~Queue (void) {
    while (p_fifo->empty() == false) Object::dref (p_fifo->pop ());
    delete p_fifo;
  }

  // return the class name

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

  // assign a queue to this one

  Queue& Queue::operator = (const Queue& that) {
    // check for self assignation
    if (this == &that) return *this;
    // lock and assign
    wrlock ();
    that.rdlock ();
    try {
      // remove the old queue
      while (p_fifo->empty() == false) Object::dref (p_fifo->pop());
      delete p_fifo; p_fifo = nullptr;
      // allocate the queue
      p_fifo = new t_fifo<Object*>;
      // copy by getter
      long flen = that.p_fifo->length (); p_fifo->resize (flen);
      for (long k = 0L; k < flen; k++) {
	p_fifo->push (Object::iref (that.p_fifo->get(k)));
      }
      // unlock and return
      unlock ();
      that.unlock ();
      return *this;
    } catch (...) {
      unlock ();
      that.unlock ();
      throw;
    }
  }

  // reset this queue class

  void Queue::reset (void) {
    wrlock ();
    try {
      while (p_fifo->empty() == false) Object::dref (p_fifo->pop());
      p_fifo->reset ();
      d_cvar.reset  ();
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // get the queue size

  long Queue::getsize (void) const {
    rdlock ();
    try {
      long result = p_fifo->getsize ();
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // get the queue length

  long Queue::length (void) const {
    rdlock ();
    try {
      long result = p_fifo->length ();
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // return true if the queue is empty

  bool Queue::empty (void) const {
    rdlock ();
    try {
      bool result = p_fifo->empty ();
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // return true if the queue is full

  bool Queue::full (void) const {
    rdlock ();
    try {
      bool result = p_fifo->full ();
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // push an object into the queue

  void Queue::push (Object* obj) {
    // lock and push
    wrlock ();
    try {
      // check for full (but not empty ah ah)
      while ((p_fifo->empty() == false) && (p_fifo->full () == true)) {
	// lock the condition variable
	d_cvar.lock ();
	// unlock the object
	unlock ();
	// wait for marking
	d_cvar.wait (false);
	// remove the condition variable lock
	d_cvar.rmlock ();
	// relock the object
	wrlock ();
      }
      // push the object
      p_fifo->push (Object::iref (obj));
      // notify the waiting objects
      d_cvar.mark ();
      // all done
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // pop an object from the queue

  Object* Queue::pop (void) {
    wrlock ();
    try {
      // check for empty
      while (p_fifo->empty () == true) {
	// lock the condition variable
	d_cvar.lock ();
	// unlock the object
	unlock ();
	// wait for marking
	d_cvar.wait (false);
	// remove the condition variable lock
	d_cvar.rmlock ();
	// relock the object
	wrlock ();
      }
      // collect the object
      Object* result = p_fifo->pop ();
      Object::tref (result);
      // notify the waiting objects
      d_cvar.mark ();
      // all done
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // get a queue object by index

  Object* Queue::get (const long index) const {
    rdlock ();
    try {
      // check that we are bounded
      if ((index < 0) || (index >= p_fifo->length ())) {
	throw Exception ("index-error","queue index is out of range");
      }
      // get the object and unlock
      Object* result = p_fifo->get (index);
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // resize the queue

  void Queue::resize (const long size) {
    wrlock ();
    try {
      p_fifo->resize (size);
      unlock ();	
    } 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_GET     = zone.intern ("get");
  static const long QUARK_POP     = zone.intern ("pop");
  static const long QUARK_PUSH    = zone.intern ("push");
  static const long QUARK_RESET   = zone.intern ("reset");
  static const long QUARK_FULLP   = zone.intern ("full-p");
  static const long QUARK_EMPTYP  = zone.intern ("empty-p");
  static const long QUARK_RESIZE  = zone.intern ("resize");
  static const long QUARK_LENGTH  = zone.intern ("length");
  static const long QUARK_GETSIZE = zone.intern ("get-size");
  
  // create a new object in a generic way

  Object* Queue::mknew (Vector* argv) {
    long argc = (argv == nullptr) ? 0 : argv->length ();

    // check 0 argument
    if (argc == 0) return new Queue;
    // check 1 argument
    if (argc == 1) {
      long size = argv->getlong (0);
      return new Queue (size);
    }
    throw Exception ("argument-error", "too many argument for queue");
  }

  // return true if the given quark is defined
  
  bool Queue::isquark (const long quark, const bool hflg) const {
    rdlock ();
    try {
      if (zone.exists (quark) == true) {
	unlock ();
	return true;
      }
      bool result = hflg ? Object::isquark (quark, hflg) : false;
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // apply this object class with a set of arguments and a quark
  
  Object* Queue::apply (Evaluable* zobj, Nameset* nset, const long quark,
		       Vector* argv) {
    // get the number of arguments
    long argc = (argv == nullptr) ? 0 : argv->length ();
    
    // dispatch 0 argument
    if (argc == 0) {
      if (quark == QUARK_FULLP)   return new Boolean (full    ());
      if (quark == QUARK_EMPTYP)  return new Boolean (empty   ());
      if (quark == QUARK_LENGTH)  return new Integer (length  ());
      if (quark == QUARK_GETSIZE) return new Integer (getsize ());
      if (quark == QUARK_RESET) {
	reset ();
	return nullptr;
      }
      if (quark == QUARK_POP) {
	wrlock ();
	try {
	  Object* result = pop ();
	  zobj->post (result);
	  unlock ();
	  return result;
	} catch (...) {
	  unlock ();
	  throw;
	}
      }
    }
    // dispatch 1 argument
    if (argc == 1) {
      if (quark == QUARK_PUSH) {
	Object* obj = argv->get (0);
	push (obj);
	return nullptr;
      }
      if (quark == QUARK_GET) {
	long index = argv->getlong (0);
	rdlock ();
	try {
	  Object* result = get (index);
	  zobj->post (result);
	  unlock ();
	  return result;
	} catch (...) {
	  unlock ();
	  throw;
	}
      }
      if (quark == QUARK_RESIZE) {
	long size = argv->getlong (0);
	resize (size);
	return nullptr;
      }
    }
    // apply these arguments with the object
    return Object::apply (zobj, nset, quark, argv);
  }
}
