/***************************************************************************
**
**  This file is part of TapePositioningSystem.
**
**  TapePositioningSystem is free software: you can redistribute it and/or modify
**  it under the terms of the GNU General Public License as published by
**  the Free Software Foundation, either version 3 of the License, or
**  (at your option) any later version.
**
**  TapePositioningSystem 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.  See the
**  GNU General Public License for more details.
**
**  You should have received a copy of the GNU General Public License
**  along with Foobar.  If not, see <http://www.gnu.org/licenses/>
**
**  See http://www.geopsy.org for more information.
**
**  Created: 2012-11-15
**  Copyright: 2012-2019
**    Marc Wathelet (ISTerre, Grenoble, France)
**
***************************************************************************/

#include "Node.h"
#include "Cluster.h"

namespace TapePositioningSystem {

  /*!
    \class Node Node.h
    \brief Brief description of class still missing

    Full description of class still missing
  */

  void Node::addDistance(Node * to, double value)
  {
    TRACE;
    QMap<Node *, double>::iterator it=_distances.find(to);
    if(it==_distances.end()) {
      _distances.insert(to, value);
    } else if(it.value()!=value) {
      it.value()=value;
    }
  }

  /*!
    Returns -1 if this node is not connected to node \a to.
  */
  double Node::distance(Node * to) const
  {
    TRACE;
    QMap<Node *, double>::const_iterator it=_distances.find(to);
    if(it!=_distances.end()) {
      return it.value();
    } else {
      return -1.0;
    }
  }

  QList<Cluster *> Node::robustQuads(double stddev)
  {
    TRACE;
    QList<Cluster *> quads;
    if(connectionCount()<3) {
      return quads;
    }

    // Tries to create all possible combination
    QList<Node *> neighbors=_distances.keys();
    int n=neighbors.count();
    for(int i=0; i<n; i++) {
      for(int j=i+1; j<n; j++) {
        for(int k=j+1; k<n; k++) {
          QList<Node *> group;
          group.append(neighbors.at(i));
          group.append(neighbors.at(j));
          group.append(neighbors.at(k));
          Cluster * quad=createRobustQuad(group, stddev);
          if(quad) {
            quads.append(quad);
          }
        }
      }
    }
    return quads;
  }

  Cluster * Node::createRobustQuad(QList<Node *> neighbors, double stddev)
  {
    TRACE;
    Cluster * c=new Cluster;
    c->setOrigin(this);
    if(c->setQuad(neighbors) && c->isRobustQuad(stddev)) {
      return c;
    } else {
      delete c;
      return 0;
    }
  }

} // namespace TapePositioningSystem
