/* -*- C++ -*-
 * src/lemon/array_map.h - Part of LEMON, a generic C++ optimization library
 *
 * Copyright (C) 2005 Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
 * (Egervary Combinatorial Optimization Research Group, EGRES).
 *
 * Permission to use, modify and distribute this software is granted
 * provided that this copyright notice appears in all copies. For
 * precise terms see the accompanying LICENSE file.
 *
 * This software is provided "AS IS" with no warranty of any kind,
 * express or implied, and with no claim as to its suitability for any
 * purpose.
 *
 */

#ifndef LEMON_ARRAY_MAP_H
#define LEMON_ARRAY_MAP_H

#include <memory>

///\ingroup graphmaps
///\file
///\brief Graph maps that construates and destruates
///their elements dynamically.

namespace lemon {


  /// \addtogroup graphmaps
  /// @{
	
  /** The ArrayMap template class is graph map structure what
   *  automatically updates the map when a key is added to or erased from
   *  the map. This map factory uses the allocators to implement 
   *  the container functionality.
   *
   *  The template parameter is the MapRegistry that the maps
   *  will belong to and the Value.
   */

  template <typename _Graph, 
	    typename _Item,
	    typename _ItemIt,
	    typename _Value>
  class ArrayMap : public AlterationNotifier<_Item>::ObserverBase {

  public:
		
    /// The graph type of the maps. 
    typedef _Graph Graph;
    /// The key type of the maps.
    typedef _Item Key;

    typedef AlterationNotifier<_Item> Registry;

  private:
    /// The iterator to iterate on the keys.
    typedef _ItemIt KeyIt;

    /// The MapBase of the Map which imlements the core regisitry function.
    typedef typename Registry::ObserverBase Parent;
		
    
  public:

    /// The value type of the map.
    typedef _Value Value;
    /// The reference type of the map;
    typedef Value& Reference;
    /// The pointer type of the map;
    typedef Value* Pointer;

    /// The const value type of the map.
    typedef const Value ConstValue;
    /// The const reference type of the map;
    typedef const Value& ConstReference;
    /// The pointer type of the map;
    typedef const Value* ConstPointer;


  private:
    typedef std::allocator<Value> Allocator;


  public:

    /** Graph and Registry initialized map constructor.
     */
    ArrayMap(const Graph& _g) : graph(&_g) {
      attach(_g.getNotifier(_Item()));
      allocate_memory();
      for (KeyIt it(*graph); it != INVALID; ++it) {
	int id = graph->id(it);;
	allocator.construct(&(values[id]), Value());
      }								
    }

    /// Constructor to use default value to initialize the map. 

    /// It constrates a map and initialize all of the the map. 

    ArrayMap(const Graph& _g, const Value& _v) : graph(&_g) {
      attach(_g.getNotifier(_Item()));
      allocate_memory();
      for (KeyIt it(*graph); it != INVALID; ++it) {
	int id = graph->id(it);;
	allocator.construct(&(values[id]), _v);
      }								
    }

    /** Constructor to copy a map of the same map type.
     */
    ArrayMap(const ArrayMap& copy) {
      if (copy.attached()) {
	attach(*copy.getRegistry());
      }
      capacity = copy.capacity;
      if (capacity == 0) return;
      values = allocator.allocate(capacity);
      for (KeyIt it(*graph); it != INVALID; ++it) {
	int id = graph->id(it);;
	allocator.construct(&(values[id]), copy.values[id]);
      }
    }

    using Parent::attach;
    using Parent::detach;
    using Parent::attached;

    /** Assign operator to copy a map of the same map type.
     */
    ArrayMap& operator=(const ArrayMap& copy) {
      if (&copy == this) return *this;
      
      if (graph != copy.graph) {
	if (attached()) {
	  clear();
	  detach();
	}
	if (copy.attached()) {
	  attach(*copy.getRegistry());
	}
	capacity = copy.capacity;
	if (capacity == 0) return *this;
	values = allocator.allocate(capacity);      
      }

      for (KeyIt it(*graph); it != INVALID; ++it) {
	int id = graph->id(it);;
	allocator.construct(&(values[id]), copy.values[id]);
      }

      return *this;
    }

    /** The destructor of the map.
     */
    virtual ~ArrayMap() {      
      if (attached()) {
	clear();
	detach();
      }
    }
	
	
    /**
     * The subscript operator. The map can be subscripted by the
     * actual keys of the graph. 
     */
    Reference operator[](const Key& key) {
      int id = graph->id(key);
      return values[id];
    } 
		
    /**
     * The const subscript operator. The map can be subscripted by the
     * actual keys of the graph. 
     */
    ConstReference operator[](const Key& key) const {
      int id = graph->id(key);
      return values[id];
    }
	
    /** Setter function of the map. Equivalent with map[key] = val.
     *  This is a compatibility feature with the not dereferable maps.
     */
    void set(const Key& key, const Value& val) {
      (*this)[key] = val;
    }
		
    /** Add a new key to the map. It called by the map registry.
     */
    void add(const Key& key) {
      int id = graph->id(key);
      if (id >= capacity) {
	int new_capacity = (capacity == 0 ? 1 : capacity);
	while (new_capacity <= id) {
	  new_capacity <<= 1;
	}
	Value* new_values = allocator.allocate(new_capacity);
	for (KeyIt it(*graph); it != INVALID; ++it) {
	  int jd = graph->id(it);;
	  if (id != jd) {
	    allocator.construct(&(new_values[jd]), values[jd]);
	    allocator.destroy(&(values[jd]));
	  }
	}
	if (capacity != 0) allocator.deallocate(values, capacity);
	values = new_values;
	capacity = new_capacity;
      }
      allocator.construct(&(values[id]), Value());
    }
		
    /** Erase a key from the map. It called by the map registry.
     */
    void erase(const Key& key) {
      int id = graph->id(key);
      allocator.destroy(&(values[id]));
    }

    void build() {
      allocate_memory();
      for (KeyIt it(*graph); it != INVALID; ++it) {
	int id = graph->id(it);;
	allocator.construct(&(values[id]), Value());
      }								
    }

    void clear() {	
      if (capacity != 0) {
	for (KeyIt it(*graph); it != INVALID; ++it) {
	  int id = graph->id(it);;
	  allocator.destroy(&(values[id]));
	}								
	allocator.deallocate(values, capacity);
	capacity = 0;
      }
    }

//     /// The stl compatible pair iterator of the map.
//     typedef MapIterator<ArrayMap> Iterator;
//     /// The stl compatible const pair iterator of the map.
//     typedef MapConstIterator<ArrayMap> ConstIterator;

//     /** Returns the begin iterator of the map.
//      */
//     Iterator begin() {
//       return Iterator(*this, KeyIt(*MapBase::getGraph()));
//     }

//     /** Returns the end iterator of the map.
//      */
//     Iterator end() {
//       return Iterator(*this, INVALID);
//     }

//     /** Returns the begin ConstIterator of the map.
//      */
//     ConstIterator begin() const {
//       return ConstIterator(*this, KeyIt(*MapBase::getGraph()));
//     }

//     /** Returns the end const_iterator of the map.
//      */
//     ConstIterator end() const {
//       return ConstIterator(*this, INVALID);
//     }

//     /// The KeySet of the Map.
//     typedef MapConstKeySet<ArrayMap> ConstKeySet;

//     /// KeySet getter function.
//     ConstKeySet keySet() const {
//       return ConstKeySet(*this); 
//     }

//     /// The ConstValueSet of the Map.
//     typedef MapConstValueSet<ArrayMap> ConstValueSet;

//     /// ConstValueSet getter function.
//     ConstValueSet valueSet() const {
//       return ConstValueSet(*this);
//     }

//     /// The ValueSet of the Map.
//     typedef MapValueSet<ArrayMap> ValueSet;

//     /// ValueSet getter function.
//     ValueSet valueSet() {
//       return ValueSet(*this);
//     }

  private:
      
    void allocate_memory() {
      int max_id = graph->maxId(_Item());
      if (max_id == -1) {
	capacity = 0;
	values = 0;
	return;
      }
      capacity = 1;
      while (capacity <= max_id) {
	capacity <<= 1;
      }
      values = allocator.allocate(capacity);	
    }      

    const Graph* graph;
    int capacity;
    Value* values;
    Allocator allocator;

  public:
//     // STL  compatibility typedefs.
//     typedef Iterator iterator;
//     typedef ConstIterator const_iterator;
//     typedef typename Iterator::PairValue value_type;
//     typedef typename Iterator::Key key_type;
//     typedef typename Iterator::Value data_type;
//     typedef typename Iterator::PairReference reference;
//     typedef typename Iterator::PairPointer pointer;
//     typedef typename ConstIterator::PairReference const_reference;
//     typedef typename ConstIterator::PairPointer const_pointer;
//     typedef int difference_type;		
  };		

  template <typename _Base> 
  class ArrayMappableGraphExtender : public _Base {
  public:

    typedef ArrayMappableGraphExtender<_Base> Graph;
    typedef _Base Parent;

    typedef typename Parent::Node Node;
    typedef typename Parent::NodeIt NodeIt;
    typedef typename Parent::NodeNotifier NodeObserverRegistry;

    typedef typename Parent::Edge Edge;
    typedef typename Parent::EdgeIt EdgeIt;
    typedef typename Parent::EdgeNotifier EdgeObserverRegistry;

    

    template <typename _Value>
    class NodeMap : public ArrayMap<Graph, Node, NodeIt, _Value> {
    public:
      typedef ArrayMappableGraphExtender<_Base> Graph;

      typedef typename Graph::Node Node;
      typedef typename Graph::NodeIt NodeIt;

      typedef ArrayMap<Graph, Node, NodeIt, _Value> Parent;

      //typedef typename Parent::Graph Graph;
      typedef typename Parent::Value Value;

      NodeMap(const Graph& g) 
	: Parent(g) {}
      NodeMap(const Graph& g, const Value& v) 
	: Parent(g, v) {}

    };

    template <typename _Value>
    class EdgeMap : public ArrayMap<Graph, Edge, EdgeIt, _Value> {
    public:
      typedef ArrayMappableGraphExtender<_Base> Graph;

      typedef typename Graph::Edge Edge;
      typedef typename Graph::EdgeIt EdgeIt;

      typedef ArrayMap<Graph, Edge, EdgeIt, _Value> Parent;

      //typedef typename Parent::Graph Graph;
      typedef typename Parent::Value Value;

      EdgeMap(const Graph& g) 
	: Parent(g) {}
      EdgeMap(const Graph& g, const Value& v) 
	: Parent(g, v) {}

    };
    
  };

/// @}

}

#endif //LEMON_ARRAY_MAP_H
