/////////////////////////////////////////////////////////////
//                                                         //
// Copyright (c) 2007-2014 by The University of Queensland //
// Centre for Geoscience Computing                         //
// http://earth.uq.edu.au/centre-geoscience-computing      //
//                                                         //
// Primary Business: Brisbane, Queensland, Australia       //
// Licensed under the Open Software License version 3.0    //
// http://www.opensource.org/licenses/osl-3.0.php          //
//                                                         //
/////////////////////////////////////////////////////////////

#include "CylinderWithJointSet.h"

//--- 
#include <cmath>
#include <cstdlib>

using std::cos;
using std::sin; 
using std::fabs; 

// --- STL includes ---
#include <utility>

using std::make_pair;

CylinderWithJointSet::CylinderWithJointSet()
{ }

CylinderWithJointSet::CylinderWithJointSet(const Vector3& c,const Vector3& axis,double l,double r): CylinderVol(c,axis,l,r)
{ }

const map<double,const AGeometricObject*> CylinderWithJointSet::getClosestObjects(const Vector3& P,int) const
{
  map<double,const AGeometricObject*> res;
  
  res.insert(make_pair(m_cyl.getDist(P),&m_cyl));
  res.insert(make_pair(m_bottom.getDist(P),&m_bottom));
  res.insert(make_pair(m_top.getDist(P),&m_top));

  for(vector<Triangle3D>::const_iterator iter=m_joints.begin();
      iter!=m_joints.end();
      iter++){
    double ndist=iter->getDist(P);
    res.insert(make_pair(ndist,&(*iter)));
  }

  return res;
}

void CylinderWithJointSet::addJoints(const TriPatchSet& t)
{
  for(vector<Triangle3D>::const_iterator iter=t.triangles_begin();
      iter!=t.triangles_end();
      iter++){
    m_joints.push_back(*iter);
  }
}

bool CylinderWithJointSet::isIn(const Sphere& S)
{ 
  double r=S.Radius();
  Vector3 p=S.Center();

  // check inside & planes via base class
  bool res=CylinderVol::isIn(S);

  if(res){
    // check intersection with joints
    vector<Triangle3D>::iterator iter=m_joints.begin();
    double dist=2*r;
    while((iter!=m_joints.end()) && res){
      dist=iter->getDist(p);
      res=(dist>r);
      iter++;
    }
  }

  return res;
}

ostream& operator << (ostream& ost,const CylinderWithJointSet& T)
{
   return ost;
}

