
#include <WFX/renderer/FirstPersonCamera.h>
#include <WFX/input/InputHandler.h>

using namespace WFX;
using namespace WFX::renderer;
using namespace WFX::math;
using namespace WFX::input;

FirstPersonCamera::FirstPersonCamera(WFX::renderer::RenderWindow* r) : Camera() {
    RenderWindow = r;
    MovingForward = false;
    MovingBack = false;
    MovingLeft = false;
    MovingRight = false;
    InputHandler::getInstance().addKeyboardListener(this);
    InputHandler::getInstance().addMouseListener(this);
}

FirstPersonCamera::~FirstPersonCamera() {
}

void FirstPersonCamera::mouseMoved(WFX::input::MouseMotionEvent e) {
    UInt middleX = RenderWindow->getWidth() >> 1;
    UInt middleY = RenderWindow->getHeight() >> 1;

    if (!e.XRel && !e.YRel)
        //nothing to do - ignore
        return;

    if (e.X == middleX && e.Y == middleY)
        //probably a warp - ignore
        return;


    //e.printDebug();

    Real angleY = 0.0f;
    Real angleZ = 0.0f;
    static Real currentRotX = 0.0f;

    angleY = (Real)e.XRel/-500.0f;
    angleZ = (Real)e.YRel/-500.0f;

    currentRotX -= angleZ;

    if (currentRotX > 1.0f) {
        currentRotX = 1.0f;
    } else if (currentRotX < -1.0f) {
        currentRotX = -1.0f;
    } else {
        rotate(angleZ);
        Vector3 uY = Vector3::UNITY;
        rotate(angleY,uY);
    }

}

void FirstPersonCamera::update() {
    Real speed = 0.5f;

    if (MovingForward)
        walk(speed);
    if (MovingBack)
        walk(-speed);
    if (MovingLeft)
        strafe(-speed);
    if (MovingRight)
        strafe(speed);
    
    Camera::update();
}

void FirstPersonCamera::mouseButtonPressed(WFX::input::MouseButtonEvent e) {
}

void FirstPersonCamera::mouseButtonReleased(WFX::input::MouseButtonEvent e) {
}

void FirstPersonCamera::keyPressed(WFX::input::KeyEvent k) {
    if (k.Key == WFXK_w)
        MovingForward = true;
    if (k.Key == WFXK_s)
        MovingBack = true;
    if (k.Key == WFXK_a)
        MovingLeft = true;
    if (k.Key == WFXK_d)
        MovingRight = true;
}

void FirstPersonCamera::keyReleased(WFX::input::KeyEvent k) {
    if (k.Key == WFXK_w)
        MovingForward = false;
    if (k.Key == WFXK_s)
        MovingBack = false;
    if (k.Key == WFXK_a)
        MovingLeft = false;
    if (k.Key == WFXK_d)
        MovingRight = false;
}


