/**
 * Copyright (C) 2016  Alexander Schmidt
 *
 * This file is part of Seamulator.
 *
 * Seamulator is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Seamulator is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Seamulator.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "seaview.h"

#include <cmath>

#include <GL/glut.h>

SeaView::SeaView(double distance, double azimuth, double altitude) :
  m_distance{distance},
  m_azimuth{azimuth},
  m_altitude{altitude}
{
}

void SeaView::onMouseEvent(int button, int state, int x, int y)
{
  if (button == 3 && state == 0) {
    m_distance += m_distance*DISTANCE_MULTIPLIER;
    glutPostRedisplay();
  }
  else if (button == 4 && state == 0) {
    m_distance -= m_distance*DISTANCE_MULTIPLIER;
    glutPostRedisplay();
  }
  else if (button == 0 && state == 0) {
    m_mouseDownPos[0] = x;
    m_mouseDownPos[1] = y;
    m_mouseDownAzimuth = m_azimuth;
    m_mouseDownAltitude = m_altitude;
  }
}

void SeaView::onMouseMove(int x, int y)
{
  m_altitude =
    fmod(m_mouseDownAltitude +
	 (double)((y - m_mouseDownPos[1]) *
		  2*M_PI / glutGet(GLUT_WINDOW_HEIGHT)),
	 (double)(2*M_PI));

  m_azimuth =
    fmod(m_mouseDownAzimuth +
	 (double)((x - m_mouseDownPos[0]) *
		  2*M_PI / glutGet(GLUT_WINDOW_WIDTH)),
	 (double)(2*M_PI));

  glutPostRedisplay();
}

void SeaView::setupView() const
{
  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();

  const double eyePos[3] =
    {m_distance * cos(m_altitude) * sin(m_azimuth),
     m_distance * cos(m_altitude) * cos(m_azimuth),
     m_distance * sin(m_altitude)};

  gluLookAt(eyePos[0], eyePos[1], eyePos[2],
	    0, 0, 0,
	    0, 0, 1);
}
