/*=========================================================================

   Library: iMSTK

   Copyright (c) Kitware, Inc. & Center for Modeling, Simulation,
   & Imaging in Medicine, Rensselaer Polytechnic Institute.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0.txt

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

=========================================================================*/

#include "LineSegmentToPlaneCD.h"
#include "imstkDeviceTracker.h"

namespace imstk
{

void
LineSegmentToPlaneCD::computeCollisionData()
{
    // Clear collisionData
    m_colData.clearAll();

    Vec3d devicePosition = m_tracker->getPosition();
    Mat3d deviceOrientation = m_tracker->getRotation().toRotationMatrix();

    m_currentStartPoint = deviceOrientation*m_startPoint + devicePosition;
    m_currentEndPoint = deviceOrientation*m_endPoint + devicePosition;  
    
    // Get plane properties
    auto planePos = m_plane->getPosition();    
    auto planeNormal = m_plane->getNormal();  

    // Do the collision
    auto peneDistance1 = -(planePos - m_currentStartPoint).dot(planeNormal);
    auto peneDistance2 = -(planePos - m_currentEndPoint).dot(planeNormal);
    
    if (peneDistance1 <= 0.0 || peneDistance2 <= 0.0)
    {
        bool firstNode;
        if (peneDistance1 <= 0.0)
        {
            firstNode = true;
            if (peneDistance2 <= 0.0 && peneDistance2 < peneDistance1)
            {
                firstNode = false;              
            }            
        }
        else
        {
            firstNode = false;
        }

        /*if (firstNode)
            std::cout << "FirstNode " << peneDistance1 << std::endl;
        else
            std::cout << "SecondNode " << peneDistance2 << std::endl;*/

        auto direction = planeNormal * -(firstNode ? peneDistance1 : peneDistance2);
        m_colData.PDColData.push_back({ (firstNode ? m_currentStartPoint : m_currentEndPoint) + direction,
                                        firstNode ? m_currentStartPoint : m_currentEndPoint, 
                                        direction, 
                                        std::abs(firstNode ? peneDistance1 : peneDistance2)});
    }
    /* else
     {
         std::cout << "NONE" << std::endl;
     }*/
}

} // imstk
