// ---------------------------------------------------------------------------
// - Trie.cpp                                                                -
// - standard object library - trie object 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 "Trie.hpp"
#include "Vector.hpp"
#include "Boolean.hpp"
#include "Integer.hpp"
#include "Runnable.hpp"
#include "QuarkZone.hpp"
#include "Exception.hpp"
 
namespace afnix {

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

  // the trie structure - all methods operate by looking at the next
  // link - this approach permits to operate with an empty root tree
  struct s_trie {
    // the character reference
    t_quad d_cref;
    // the terminal flag
    bool   d_term;
    // the object reference
    Object* p_robj;
    // the left link
    s_trie* p_llnk;
    // the right link
    s_trie* p_rlnk;
    // the next element
    s_trie* p_next;
    // create a default trie element
    s_trie (void) {
      d_cref = nilq;
      d_term = false;
      p_robj = nilp;
      p_llnk = nilp;
      p_rlnk = nilp;
      p_next = nilp;
    }
    // create a default trie element
    s_trie (const t_quad c) {
      d_cref = c;
      d_term = false;
      p_robj = nilp;
      p_llnk = nilp;
      p_rlnk = nilp;
      p_next = nilp;
    }
    // destroy this trie element
    ~s_trie (void) {
      Object::dref (p_robj);
      delete p_next;
      delete p_rlnk;
    }
    // get the number of elements
    long length (void) const {
      // initialize result
      long result = d_term ? 1 : 0;
      // look at the right elements
      if (p_rlnk != nilp) result += p_rlnk->length ();
      // look at the next elements
      if (p_next != nilp) result += p_next->length ();
      // here it is
      return result;
    }
    // return find the next trie element
    s_trie* find (const t_quad c) const {
      // initialize with the next element
      s_trie* elem = p_next;
      // iterate with the right links
      while (elem != nilp) {
	if (elem->d_cref == c) return elem;
	elem = elem->p_rlnk;
      }
      return nilp;
    }
    // set or create the next element
    s_trie* add (const t_quad c) {
      // check the next element
      if (p_next == nilp) {
	p_next = new s_trie (c);
	return p_next;
      }
      // check for first entry
      if (c < p_next->d_cref) {
	s_trie* elem = new s_trie (c);
	elem->p_rlnk = p_next;
	p_next->p_llnk = elem;
	p_next = elem;
	return elem;
      }
      // look into right line
      s_trie* elem = p_next;
      while (elem != nilp){
	if (elem->d_cref == c) return elem;
	if (elem->p_rlnk == nilp) {
	  elem->p_rlnk = new s_trie (c);
	  elem->p_rlnk->p_llnk = elem;
	  return elem->p_rlnk;
	} else {
	  if (c < elem->p_rlnk->d_cref) {
	    s_trie* helm = new s_trie (c);
	    helm->p_rlnk = elem->p_rlnk;
	    elem->p_llnk = helm;
	    elem->p_rlnk = helm;
	    helm->p_llnk = elem;
	    return helm;
	  }
	}
	elem = elem->p_rlnk;
      }
      throw Exception ("internal-error", "end of trie list reached in add");
    }
  };
  
  // -------------------------------------------------------------------------
  // - class section                                                         -
  // -------------------------------------------------------------------------

  // create a default trie

  Trie::Trie (void) {
    p_tree = new s_trie;
  }

  // destroy tthis trie
  
  Trie::~Trie (void) {
    delete p_tree;
  }
  
  // return the class name
  
  String Trie::repr (void) const {
    return "Trie";
  }
  
  // reset this trie

  void Trie::reset (void) {
    delete p_tree;
    p_tree = new s_trie;
  }

  // return the number of elements

  long Trie::length (void) const {
    rdlock ();
    long result = p_tree->length ();
    unlock ();
    return result;
  }

  // return true if a word exists in the trie

  bool Trie::exists (const String& word) const {
    // do nothing with a nil word
    if (word.isnil () == true) return false;
    // lock and check
    rdlock ();
    try {
      // get the trie tree
      s_trie* elem = p_tree;
      // loop in the word
      long wlen = word.length ();
      for (long i = 0; i < wlen; i++) {
	t_quad c = word[i];
	elem = elem->find (c);
	if (elem == nilp) break;
      }
      bool result = (elem == nilp) ? false : elem->d_term;
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // set a binding by word and object

  void Trie::add (const String& word, Object* wobj) {
    // do nothing with a nil word
    if (word.isnil () == true) return;
    // lock and bind
    wrlock ();
    try {
      // get the trie tree
      s_trie* elem = p_tree;
      // loop in the word
      long wlen = word.length ();
      for (long i = 0; i < wlen; i++) {
	t_quad c = word[i];
	elem = elem->add (c);
      }
      // set the trie object
      elem->d_term = true;
      Object::iref (wobj);
      Object::dref (elem->p_robj);
      elem->p_robj = wobj;
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // get an object by word

  Object* Trie::get (const String& word) const {
    // do nothing with a nil word
    if (word.isnil () == true) return nilp;
    // lock and check
    rdlock ();
    try {
      // get the trie tree
      s_trie* elem = p_tree;
      // loop in the word
      long wlen = word.length ();
      for (long i = 0; i < wlen; i++) {
	t_quad c = word[i];
	elem = elem->find (c);
	if (elem == nilp) break;
      }
      // get the element result
      Object* result = nilp;
      if ((elem != nilp) && (elem->d_term == true)) result = elem->p_robj;
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // get an object by word of throw an exception

  Object* Trie::lookup (const String& word) const {
    // do nothing with a nil word
    if (word.isnil () == true) {
      throw Exception ("lookup-error", "cannot lookup with nil word");
    }
    // lock and check
    rdlock ();
    try {
      // get the trie tree
      s_trie* elem = p_tree;
      // loop in the word
      long wlen = word.length ();
      for (long i = 0; i < wlen; i++) {
	t_quad c = word[i];
	elem = elem->find (c);
	if (elem == nilp) break;
      }
      // get the element result
      if ((elem == nilp) || (elem->d_term == false)) {
	throw Exception ("lookup-error", "cannot find word", word);
      }
      Object* result = elem->p_robj;
      unlock ();
      return result;
    } 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_RESET  = zone.intern ("reset");
  static const long QUARK_LENGTH = zone.intern ("length");
  static const long QUARK_LOOKUP = zone.intern ("lookup");
  static const long QUARK_EXISTS = zone.intern ("exists-p");
  
  // create a new object in a generic way
  
  Object* Trie::mknew (Vector* argv) {
    long argc = (argv == nilp) ? 0 : argv->length ();
    // check for 0 argument
    if (argc == 0) return new Trie;
    throw Exception ("argument-error", "too many arguments with trie");
  }
  
  // return true if the given quark is defined
  
  bool Trie::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* Trie::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_EXISTS) {
	String word = argv->getstring (0);
	return new Boolean (exists (word));
      }
      if (quark == QUARK_GET) {
	String word = argv->getstring (0);
	rdlock ();
	try {
	  Object* result = get (word);
	  robj->post (result);
	  unlock ();
	  return result;
	} catch (...) {
	  unlock ();
	  throw;
	}
      }
      if (quark == QUARK_LOOKUP) {
	String word = argv->getstring (0);
	rdlock ();
	try {
	  Object* result = lookup (word);
	  robj->post (result);
	  unlock ();
	  return result;
	} catch (...) {
	  unlock ();
	  throw;
	}
      }
    }
    // dispatch 2 arguments
    if (argc == 2) {
      if (quark == QUARK_ADD) {
	String  word = argv->getstring (0);
	Object* wobj = argv->get (1);
	add (word, wobj);
	return nilp;
      }
    }
    // call the object method
    return Object::apply (robj, nset, quark, argv);
  }
}
