/////////////////////////////////////////////////////////////
//                                                         //
// Copyright (c) 2007-2017 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.apache.org/licenses/LICENSE-2.0              //
//                                                         //
/////////////////////////////////////////////////////////////

#include "SphereSectionVol.h"

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

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

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

using std::make_pair;

SphereSectionVol::SphereSectionVol()
{}

SphereSectionVol::SphereSectionVol(const Vector3& c,const double r,const double h, const Vector3& n)
{
  m_sph=SphereIn(c,r);
  m_section_dist = h;
  m_section_normal = n;
}

pair<Vector3,Vector3> SphereSectionVol::getBoundingBox()
{
  Vector3 r=Vector3(m_sph.Radius(),m_sph.Radius(),m_sph.Radius());
  return make_pair(m_sph.Center()-r,m_sph.Center()+r);
}

Vector3 SphereSectionVol::getAPoint(int) const
{
  double r=m_sph.Radius()*((double)(rand())/(double)(RAND_MAX));
  double phi=M_PI*((double)(rand())/(double)(RAND_MAX));
  double rho=2*M_PI*((double)(rand())/(double)(RAND_MAX));

  return m_sph.Center()+r*Vector3(sin(phi)*cos(rho),sin(phi)*sin(rho),cos(phi));
}

const map<double,const AGeometricObject*> SphereSectionVol::getClosestObjects(const Vector3& P,int) const
{
  map<double,const AGeometricObject*> res;

  res.insert(make_pair(m_sph.getDist(P),&m_sph));

  return res;  
}

bool SphereSectionVol::isIn(const Vector3& P) const
{
  double dist;
  bool isInSection;
  Vector3 posn_vector;
  double norm_comp;

  isInSection = false;
  posn_vector = P - m_sph.Center();
  dist = posn_vector.norm();
  if (dist<m_sph.Radius()) {
     norm_comp = dot(posn_vector,m_section_normal);
     if ((norm_comp < 0)&&(fabs(norm_comp)>m_section_dist)) {
        if ((fabs(norm_comp)/dist - m_section_dist/m_sph.Radius()) > 0) {
           isInSection = true;
	}
     }
  }

  return (isInSection);
}

bool SphereSectionVol::isIn(const Sphere& S)
{
   bool isInSection;

   isInSection = false;

   if ((isIn(S.Center()))&&(m_sph.getDist(S.Center())>S.Radius())) {
      isInSection = true;
   }
  return (isInSection);
}

/*
  Check if sphere is fully outside the volume.

  \param S the sphere
  \warning DUMMY IMPLEMENTATION
*/
bool SphereSectionVol::isFullyOutside(const Sphere& S)
{
  return true;
}

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