// ---------------------------------------------------------------------------
// - Hasher.cpp                                                              -
// - afnix cryptography - base message hasher 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-2008 amaury darsch                                   -
// ---------------------------------------------------------------------------

#include "Byte.hpp"
#include "Ascii.hpp"
#include "Vector.hpp"
#include "Buffer.hpp"
#include "Hasher.hpp"
#include "Boolean.hpp"
#include "QuarkZone.hpp"

namespace afnix {

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

  // create a hasher by name and size

  Hasher::Hasher (const String& name, const long size, const long hlen) {
    d_name = name;
    d_size = size;
    p_data = new t_byte[d_size];
    d_hlen = hlen;
    p_hash = new t_byte[d_hlen];
    reset ();
  }

  // destroy this buffer
  
  Hasher::~Hasher (void) {
    delete [] p_data;    
    delete [] p_hash;
  }

  // return the class name

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

  // reset this hasher buffer

  void Hasher::reset (void) {
    wrlock ();
    d_count = 0;
    d_llen  = 0;
    d_ulen  = 0;
    for (long i = 0; i < d_size; i++) p_data[i] = nilc;
    for (long i = 0; i < d_hlen; i++) p_hash[i] = nilc;
    unlock ();
  }

  // clear the hasher buffer counter

  void Hasher::clear (void) {
    wrlock ();
    d_count = 0;
    unlock ();
  }

  // return the hasher name

  String Hasher::getname (void) const {
    rdlock ();
    String result = d_name;
    unlock ();
    return result;
  }

  // return the hash value length

  long Hasher::gethlen (void) const {
    rdlock ();
    long result = d_hlen;
    unlock ();
    return result;    
  }

  // get the hash value by index

  t_byte Hasher::gethash (const long index) const {
    rdlock ();
    if (index >= d_hlen) {
      unlock ();
      throw Exception ("index-error", "hash index is out of bound");
    }
    t_byte result = p_hash[index];
    unlock ();
    return result;
  }

  // get the hasher buffer count
  
  long Hasher::getcount (void) const {
    rdlock ();
    long result = d_count;
    unlock ();
    return result;
  }

  // get the message lower length
  
  t_octa Hasher::getllen (void) const {
    rdlock ();
    t_octa result = d_llen;
    unlock ();
    return result;
  }

  // get the message upper length
  
  t_octa Hasher::getulen (void) const {
    rdlock ();
    t_octa result = d_ulen;
    unlock ();
    return result;
  }
   
  // copy some bytes in the buffer and return the number of copied data
  
  long Hasher::copy (const t_byte* data, const long size) {
    wrlock ();
    long result = 0;
    while ((d_count < d_size) && (result < size)) {
      p_data[d_count++] = data[result++];
      if (d_llen == 0xFFFFFFFFFFFFFFFFULL) {
	d_ulen++;
	d_llen = 0;
      } else {
	d_llen++;
      }
    }
    unlock ();
    return result;
  }
  

  // copy some bytes in the buffer from a stream
  
  long Hasher::copy (Input& is) {
    wrlock ();
    try {
      long result = 0;
      while (is.valid (-1) == false) {
	p_data[d_count++] = is.read ();
	if (d_llen == 0xFFFFFFFFFFFFFFFFULL) {
	  d_ulen++;
	  d_llen = 0;
	} else {
	  d_llen++;
	}
	result++;
      }
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // compute a message hasher from a string

  String Hasher::compute (const String& msg) {
    char* data = msg.encode ();
    long  size = Ascii::strlen (data);
    wrlock ();
    try {
      process ((t_byte*) data, size);
      finish  ();
      String msgh = format ();
      reset   ();
      delete [] data;
      reset  ();
      unlock ();
      return msgh;
    } catch (...) {
      delete [] data;
      reset  ();
      unlock ();
      throw;
    }
  }

  // compute a message hasher from an input stream

  String Hasher::compute (Input& is) {
    wrlock ();
    try {
      process (is);
      finish  ();
      String msgh = format ();
      reset  ();
      unlock ();
      return msgh;
    } catch (...) {
      reset  ();
      unlock ();
      throw;
    }
  }

  // -------------------------------------------------------------------------
  // - object section                                                        -
  // -------------------------------------------------------------------------

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

  // the hasher supported quarks
  static const long QUARK_HASHP   = zone.intern ("hash-p");
  static const long QUARK_FORMAT  = zone.intern ("format");
  static const long QUARK_COMPUTE = zone.intern ("compute");
  static const long QUARK_GETNAME = zone.intern ("get-name");
  static const long QUARK_GETHASH = zone.intern ("get-hash");

  // return true if the given quark is defined

  bool Hasher::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* Hasher::apply (Runnable* robj, Nameset* nset, const long quark,
			 Vector* argv) {
    // get the number of arguments
    long argc = (argv == nilp) ? 0 : argv->length ();
    
    // check for 0 argument
    if (argc == 0) {
      if (quark == QUARK_FORMAT)  return new String (format  ());
      if (quark == QUARK_GETNAME) return new String (getname ());
    }

    // check for 1 argument
    if (argc == 1) {
      if (quark == QUARK_GETHASH) {
	long index = argv->getint (0);
	return new Byte (gethash (index));
      }
      if (quark == QUARK_HASHP) {
	String s = argv->getstring (0);
	return new Boolean (ishash (s));
      }
      if (quark == QUARK_COMPUTE) {
	Object* obj = argv->get (0);
	// check for a literal
	Literal* lval = dynamic_cast <Literal*> (obj);
	if (lval != nilp) {
	  String msg = lval->tostring ();
	  return new String (compute (msg));
	}
	// check for a buffer
	Buffer* bval = dynamic_cast <Buffer*> (obj);
	if (bval != nilp) {
	  String msg = bval->tostring ();
	  return new String (compute (msg));
	}
	// check for an input stream
	Input* is = dynamic_cast <Input*> (obj);
	if (is != nilp) return new String (compute (*is));
	// invalid object
	throw Exception ("type-error", "invalid object for hasher compute",
			 Object::repr (obj));
      }
    }

    // call the object method
    return Object::apply (robj, nset, quark, argv);
  }
}
