//------------------------------------------------------------------------------
// Project Phoenix
//
// Copyright (c) 2017-2018 RWTH Aachen University, Germany,
// Virtual Reality & Immersive Visualization Group.
//------------------------------------------------------------------------------
//                                 License
//
// Licensed under the 3-Clause BSD License (the "License");
// you may not use this file except in compliance with the License.
// See the file LICENSE for the full text.
// You may obtain a copy of the License at
//
//     https://opensource.org/licenses/BSD-3-Clause
//
// 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 "navigation_behavior.hpp"

#include <vector>

#include "glm/detail/type_vec3.hpp"
#include "glm/glm.hpp"
#include "glm/gtc/matrix_access.hpp"

#include "phx/display_system.hpp"
#include "phx/engine.hpp"
#include "phx/entity.hpp"
#include "phx/hmd.hpp"
#include "phx/scene.hpp"
#include "phx/transform.hpp"

void NavigationBehavior::OnUpdate() {
  // If there exists an HMD and a transform.
  const auto hmd = GetEntity()
                       ->GetScene()
                       ->GetEngine()
                       ->GetSystem<phx::DisplaySystem>()
                       ->GetHMD();
  const auto transform = GetEntity()->GetFirstComponent<phx::Transform>();
  if (!hmd || !transform) return;

  auto indices = hmd->GetControllerIndices();

  for (auto i = 0u; i < indices.size(); ++i) {
    vr::VRControllerState_t controller_state;
    vr::VRSystem()->GetControllerState(indices[i], &controller_state,
                                       sizeof controller_state);

    // Set the transform based on whether the trigger is pressed.
    if (controller_state.ulButtonTouched &
        vr::ButtonMaskFromId(vr::EVRButtonId::k_EButton_SteamVR_Trigger))
      transform->Translate(
          -0.05F * glm::column(hmd->GetRightControllerTransformation(), 2));
    if (controller_state.ulButtonTouched &
        vr::ButtonMaskFromId(vr::EVRButtonId::k_EButton_SteamVR_Touchpad))
      transform->Translate(
          0.05F * glm::column(hmd->GetRightControllerTransformation(), 2));
  }
}