// -*- mode:C++ -*-

#ifndef HUGO_SMART_GRAPH_H
#define HUGO_SMART_GRAPH_H

///\ingroup graphs
///\file
///\brief SmartGraph and SymSmartGraph classes.

#include <vector>
#include <climits>

#include <hugo/invalid.h>

#include <hugo/default_map_factory.h>
#include <hugo/sym_map_factory.h>
#include <hugo/map_registry.h>

#include <hugo/map_defines.h>

namespace hugo {

/// \addtogroup graphs
/// @{
//  class SymSmartGraph;

  ///A smart graph class.

  ///This is a simple and fast graph implementation.
  ///It is also quite memory efficient, but at the price
  ///that <b> it does not support node and edge deletion</b>.
  ///It conforms to the graph interface documented under
  ///the description of \ref GraphSkeleton.
  ///\sa \ref GraphSkeleton.
  ///
  ///\todo Some member functions could be \c static.
  ///
  ///\todo A possibly useful functionality: a function saveState() would
  ///give back a data sturcture X and then the function restoreState(X)
  ///would remove the nodes and edges added after the call of saveState().
  ///Of course it should be used as a stack. (Maybe X is not necessary.)
  ///
  ///\author Alpar Juttner
  class SmartGraph {

    struct NodeT 
    {
      int first_in,first_out;      
      NodeT() : first_in(-1), first_out(-1) {}
    };
    struct EdgeT 
    {
      int head, tail, next_in, next_out;      
      //FIXME: is this necessary?
      EdgeT() : next_in(-1), next_out(-1) {}  
    };

    std::vector<NodeT> nodes;

    std::vector<EdgeT> edges;
    
    
  public:

    typedef SmartGraph Graph;

    class Node;
    class Edge;

    class NodeIt;
    class EdgeIt;
    class OutEdgeIt;
    class InEdgeIt;
    
    CREATE_MAP_REGISTRIES;
    CREATE_MAPS(DefaultMapFactory);
    
  public:

    SmartGraph() : nodes(), edges() { }
    SmartGraph(const SmartGraph &_g) : nodes(_g.nodes), edges(_g.edges) { }
    
    int nodeNum() const { return nodes.size(); }  //FIXME: What is this?
    int edgeNum() const { return edges.size(); }  //FIXME: What is this?

    ///\bug This function does something different than
    ///its name would suggests...
    int maxNodeId() const { return nodes.size(); }  //FIXME: What is this?
    ///\bug This function does something different than
    ///its name would suggests...
    int maxEdgeId() const { return edges.size(); }  //FIXME: What is this?

    Node tail(Edge e) const { return edges[e.n].tail; }
    Node head(Edge e) const { return edges[e.n].head; }

    NodeIt& first(NodeIt& v) const { 
      v=NodeIt(*this); return v; }
    EdgeIt& first(EdgeIt& e) const { 
      e=EdgeIt(*this); return e; }
    OutEdgeIt& first(OutEdgeIt& e, const Node v) const { 
      e=OutEdgeIt(*this,v); return e; }
    InEdgeIt& first(InEdgeIt& e, const Node v) const { 
      e=InEdgeIt(*this,v); return e; }

    static int id(Node v) { return v.n; }
    static int id(Edge e) { return e.n; }

    Node addNode() {
      Node n; n.n=nodes.size();
      nodes.push_back(NodeT()); //FIXME: Hmmm...

      
      node_maps.add(n);
      return n;
    }
    
    Edge addEdge(Node u, Node v) {
      Edge e; e.n=edges.size(); edges.push_back(EdgeT()); //FIXME: Hmmm...
      edges[e.n].tail=u.n; edges[e.n].head=v.n;
      edges[e.n].next_out=nodes[u.n].first_out;
      edges[e.n].next_in=nodes[v.n].first_in;
      nodes[u.n].first_out=nodes[v.n].first_in=e.n;

      edge_maps.add(e);

      return e;
    }

    /// Finds an edge between two nodes.

    /// Finds an edge from node \c u to node \c v.
    ///
    /// If \c prev is \ref INVALID (this is the default value), then
    /// It finds the first edge from \c u to \c v. Otherwise it looks for
    /// the next edge from \c u to \c v after \c prev.
    /// \return The found edge or INVALID if there is no such an edge.
    Edge findEdge(Node u,Node v, Edge prev = INVALID) 
    {
      int e = (prev.n==-1)? nodes[u.n].first_out : edges[prev.n].next_out;
      while(e!=-1 && edges[e].tail!=v.n) e = edges[e].next_out;
      prev.n=e;
      return prev;
    }
    
    void clear() {
      edge_maps.clear();
      edges.clear();
      node_maps.clear();
      nodes.clear();
    }

    class Node {
      friend class SmartGraph;
      template <typename T> friend class NodeMap;
      
      friend class Edge;
      friend class OutEdgeIt;
      friend class InEdgeIt;
      friend class SymEdge;

    protected:
      int n;
      friend int SmartGraph::id(Node v); 
      Node(int nn) {n=nn;}
    public:
      Node() {}
      Node (Invalid) { n=-1; }
      bool operator==(const Node i) const {return n==i.n;}
      bool operator!=(const Node i) const {return n!=i.n;}
      bool operator<(const Node i) const {return n<i.n;}
      //      ///Validity check
      //      operator bool() { return n!=-1; }
    };
    
    class NodeIt : public Node {
      const SmartGraph *G;
      friend class SmartGraph;
    public:
      NodeIt() : Node() { }
      NodeIt(const SmartGraph& _G,Node n) : Node(n), G(&_G) { }
      NodeIt(Invalid i) : Node(i) { }
      NodeIt(const SmartGraph& _G) : Node(_G.nodes.size()?0:-1), G(&_G) { }
      NodeIt &operator++() {
	n=(n+2)%(G->nodes.size()+1)-1; 
	return *this; 
      }
//       ///Validity check
//       operator bool() { return Node::operator bool(); }      
    };

    class Edge {
      friend class SmartGraph;
      template <typename T> friend class EdgeMap;

      //template <typename T> friend class SymSmartGraph::SymEdgeMap;      
      //friend Edge SymSmartGraph::opposite(Edge) const;
      
      friend class Node;
      friend class NodeIt;
    protected:
      int n;
      friend int SmartGraph::id(Edge e);

    public:
      /// An Edge with id \c n.

      /// \bug It should be
      /// obtained by a member function of the Graph.
      Edge(int nn) {n=nn;}
      Edge() { }
      Edge (Invalid) { n=-1; }
      bool operator==(const Edge i) const {return n==i.n;}
      bool operator!=(const Edge i) const {return n!=i.n;}
      bool operator<(const Edge i) const {return n<i.n;}
      ///\bug This is a workaround until somebody tells me how to
      ///make class \c SymSmartGraph::SymEdgeMap friend of Edge
      int &idref() {return n;}
      const int &idref() const {return n;} 
//       ///Validity check
//       operator bool() { return n!=-1; }
   };
    
    class EdgeIt : public Edge {
      const SmartGraph *G;
      friend class SmartGraph;
    public:
      EdgeIt(const SmartGraph& _G) : Edge(_G.edges.size()-1), G(&_G) { }
      EdgeIt(const SmartGraph& _G, Edge e) : Edge(e), G(&_G) { }
      EdgeIt (Invalid i) : Edge(i) { }
      EdgeIt() : Edge() { }
      ///\bug This is a workaround until somebody tells me how to
      ///make class \c SymSmartGraph::SymEdgeMap friend of Edge
      int &idref() {return n;}
      EdgeIt &operator++() { --n; return *this; }
//       ///Validity check
//       operator bool() { return Edge::operator bool(); }      
    };
    
    class OutEdgeIt : public Edge {
      const SmartGraph *G;
      friend class SmartGraph;
    public: 
      OutEdgeIt() : Edge() { }
      OutEdgeIt(const SmartGraph& _G, Edge e) : Edge(e), G(&_G) { }
      OutEdgeIt (Invalid i) : Edge(i) { }

      OutEdgeIt(const SmartGraph& _G,const Node v)
	: Edge(_G.nodes[v.n].first_out), G(&_G) {}
      OutEdgeIt &operator++() { n=G->edges[n].next_out; return *this; }
//       ///Validity check
//       operator bool() { return Edge::operator bool(); }      
    };
    
    class InEdgeIt : public Edge {
      const SmartGraph *G;
      friend class SmartGraph;
    public: 
      InEdgeIt() : Edge() { }
      InEdgeIt(const SmartGraph& _G, Edge e) : Edge(e), G(&_G) { }
      InEdgeIt (Invalid i) : Edge(i) { }
      InEdgeIt(const SmartGraph& _G,Node v)
	: Edge(_G.nodes[v.n].first_in), G(&_G) { }
      InEdgeIt &operator++() { n=G->edges[n].next_in; return *this; }
//       ///Validity check
//       operator bool() { return Edge::operator bool(); }      
    };

  };

  ///Graph for bidirectional edges.

  ///The purpose of this graph structure is to handle graphs
  ///having bidirectional edges. Here the function \c addEdge(u,v) adds a pair
  ///of oppositely directed edges.
  ///There is a new edge map type called
  ///\ref SymSmartGraph::SymEdgeMap "SymEdgeMap"
  ///that complements this
  ///feature by
  ///storing shared values for the edge pairs. The usual
  ///\ref GraphSkeleton::EdgeMap "EdgeMap"
  ///can be used
  ///as well.
  ///
  ///The oppositely directed edge can also be obtained easily
  ///using \ref opposite.
  ///\warning It shares the similarity with \ref SmartGraph that
  ///it is not possible to delete edges or nodes from the graph.
  //\sa \ref SmartGraph.

  class SymSmartGraph : public SmartGraph
  {
  public:
    typedef SymSmartGraph Graph;

    KEEP_NODE_MAP(SmartGraph);
    KEEP_EDGE_MAP(SmartGraph);

    CREATE_SYM_EDGE_MAP_REGISTRY;
    CREATE_SYM_EDGE_MAP_FACTORY(DefaultMapFactory);
    IMPORT_SYM_EDGE_MAP(SymEdgeMapFactory);

    SymSmartGraph() : SmartGraph() { }
    SymSmartGraph(const SmartGraph &_g) : SmartGraph(_g) { }
    ///Adds a pair of oppositely directed edges to the graph.
    Edge addEdge(Node u, Node v)
    {
      Edge e = SmartGraph::addEdge(u,v);
      Edge f = SmartGraph::addEdge(v,u);
      sym_edge_maps.add(e);
      sym_edge_maps.add(f);
      return e;
    }

    ///The oppositely directed edge.

    ///Returns the oppositely directed
    ///pair of the edge \c e.
    static Edge opposite(Edge e)
    {
      Edge f;
      f.idref() = e.idref() - 2*(e.idref()%2) + 1;
      return f;
    }
    

  };
  
  /// @}  
} //namespace hugo




#endif //HUGO_SMART_GRAPH_H
