/*----------------------------------------------------------------------------*/
/*!
Copyright (c) 2018, 2019 by Christian Nowak a.k.a. Creestee a.k.a. chn
Contact: chnowak@web.de or creestee@creestee.com
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. This application may be used and redistributed in source code and binary
form free of charge for personal and for educational purposes.
4. Redistribution and usage of this application in source code or binary form
for commercial purposes requires explicit written permission from the
author.


THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the RadarVolumeExplorer project.
*/
/*----------------------------------------------------------------------------*/

#include <QGLFunctions>

#include "RveMap.h"
#include "GLWidget.h"
#include "RveGisData/RveShpPoint.h"

#ifndef GL_MULTISAMPLE
#define GL_MULTISAMPLE  0x809D
#endif

/*---------------------------------------------------------------------------*/
/*!*/
/*---------------------------------------------------------------------------*/
RveMap::RveMap( GLWidget *pGLWidget ) :
   QObject( pGLWidget ),
   m_pGLWidget( pGLWidget ),
   m_Lon( -DBL_MAX ),
   m_Lat( -DBL_MAX ),
   m_OromapEnabled( false ),
   m_Range( -1.0 ),
   m_RangeRingDistance( 25000.0 ),
   m_RangeRingEnabled( false ),
   m_DirectionsEnabled( false ),
   m_HeightGridEnabled( false ),
   m_HeightGridDistance( 1000.0 ),
   m_HeightGridMaxHeight( 10000.0 ),
   m_Precision( 1000 ),
   m_pDem( new RveDem() ),
   m_GLIndices( -1 ),
   m_GLVertices( -1 ),
   m_Initialized( false )
{
   m_OroColors.insert( 0, QColor( 0, 255, 0 ) );
   m_OroColors.insert( 500, QColor( 255, 255, 0 ) );
   m_OroColors.insert( 1600, QColor( 255, 0, 0 ) );
   m_OroColors.insert( 2800, QColor( 255, 255, 255 ) );
}


   /*---------------------------------------------------------------------------*/
/*!*/
/*---------------------------------------------------------------------------*/
RveMap::~RveMap()
{
   if( m_pDem )
      delete m_pDem;
   clearGisSprites();
}


void RveMap::addGisData( RveGisData *pGisData )
{
   if( !m_Gis.contains( pGisData ) )
   {
      m_Gis.append( pGisData );
      calculate();
   }
}


void RveMap::removeGisData( RveGisData *pGisData )
{
   m_Gis.removeAll( pGisData );
   calculate();
}


void RveMap::setLonLat( double lon, double lat )
{
   if( m_Lon != lon || m_Lat != lat )
   {
      m_Lon = lon;
      m_Lat = lat;
      m_ProjPnt = RveProjPnt( lon, lat );
      calculate();
   }
}

void RveMap::enableDirections( bool enabled )
{
   m_DirectionsEnabled = enabled;
}


void RveMap::enableHeightGrid( bool enabled )
{
   m_HeightGridEnabled = enabled;
}


void RveMap::setHeightGridDistance( double d )
{
   m_HeightGridDistance = d;
}


void RveMap::setHeightGridMaxHeight( double h )
{
   m_HeightGridMaxHeight = h;
}


void RveMap::setRange( double range )
{
   if ( m_Range == range )
      return;

   m_Range = range;
   m_RangeRingThickness = ( range / (double)m_Precision ) * 2.0;

   buildShapes();
   calculate();
}


void RveMap::buildShapes()
{
   foreach( RveGisData *pGisData, m_Gis )
   {
//      pCost->buildGL();
   }
}


void RveMap::enableOromap( bool enabled )
{
   if( enabled != m_OromapEnabled )
   {
      m_OromapEnabled = enabled;
      buildShapes();
      calculate();
   }
}


void RveMap::enableRangeRings( bool enabled )
{
   if( enabled != m_RangeRingEnabled )
   {
      m_RangeRingEnabled = enabled;
      calculate();
   }
}


void RveMap::setRangeRingsDistance( double d )
{
   m_RangeRingDistance = d;
   if( m_RangeRingEnabled )
   {
      calculate();
   }
}


QColor RveMap::color( qint16 h )
{
   if( h <= 0 )
      return( QColor( 0, 0, 128 ) );

   QList<int> heights = m_OroColors.keys();
   qSort( heights );

   if( h <= heights[0] )
      return( m_OroColors.value( heights[0] ) );

   if( h >= heights[heights.size() - 1] )
      return( m_OroColors.value( heights[heights.size() - 1] ) );

   int n = 0;
   for( n = 0; n < heights.size(); n++ )
   {
      if( h >= heights[n] && h <= heights[n + 1] )
      {
         qint16 h1 = heights[n];
         qint16 h2 = heights[n + 1];
         double p = (double)( h - h1 ) / (double)( h2 - h1 );
         QColor c1 = m_OroColors.value( h1 );
         QColor c2 = m_OroColors.value( h2 );
         double r = (double)c1.red()   + ( p * ( (double)c2.red()   - (double)c1.red()   ) );
         double g = (double)c1.green() + ( p * ( (double)c2.green() - (double)c1.green() ) );
         double b = (double)c1.blue()  + ( p * ( (double)c2.blue()  - (double)c1.blue()  ) );
         return( QColor( r + 0.25, g + 0.25, b + 0.25 ) );
      }
   }

   return( QColor( 0, 0, 0 ) );
}

void RveMap::paintGL()
{
   if( m_Lon == -DBL_MAX || m_Lat == -DBL_MAX )
      return;

   if( !m_Initialized )
   {
      initializeGLFunctions();
      m_Initialized = true;
   }

   glDisable( GL_LIGHTING );
   glDisable( GL_LIGHT0 );
   glDisable( GL_CULL_FACE );
   glEnable( GL_DEPTH_TEST );
   glEnable( GL_COLOR_MATERIAL );

   glBindBuffer( GL_ARRAY_BUFFER, m_GLVertices );
   glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, m_GLIndices );
   glEnableClientState( GL_VERTEX_ARRAY );
   glEnableClientState( GL_COLOR_ARRAY );
   glEnableClientState( GL_NORMAL_ARRAY );

   glVertexPointer( 3, GL_FLOAT, sizeof( RveModel::Vertex ), (char *)NULL + (0) );
   glColorPointer( 4, GL_FLOAT, sizeof( RveModel::Vertex ), (char *)NULL + /*( sizeof( RveModel::XYZ ) )*/12 );
   glNormalPointer( GL_FLOAT, sizeof( RveModel::Vertex ), (char *)NULL + ( sizeof( RveModel::XYZ ) + sizeof( RveModel::RGBA ) ) );

   glDrawElements( GL_TRIANGLES, m_Indices.size(), GL_UNSIGNED_INT, (char *)NULL + 0 );

   glDisableClientState( GL_VERTEX_ARRAY );
   glDisableClientState( GL_COLOR_ARRAY );
   glDisableClientState( GL_NORMAL_ARRAY );

   glColor3f( 1.0, 1.0, 1.0 );
   glLineWidth( 1.0 );

   //*** Directions
   if( m_DirectionsEnabled )
   {
      // North
      glPushMatrix();
   //   glRotatef( 90.0, 0.0, 0.0, -1.0 );
      glTranslatef( 0.0, m_Range, 0.0 );
      drawArrow( 0.25 * m_Range );
      glPopMatrix();

      // East
      glPushMatrix();
      glRotatef( 90.0, 0.0, 0.0, -1.0 );
      glTranslatef( 0.0, m_Range, 0.0 );
      drawArrow( 0.25 * m_Range );
      glPopMatrix();

      renderText( "N",
         0.0, m_Range + 0.3 * m_Range, 0.0,
         1000.0, 1000.0,
         "Arial", 20 );

      renderText( "E",
         m_Range + 0.3 * m_Range, 0.0, 0.0,
         1000.0, 1000.0,
         "Arial", 20 );

      //*** Box
      glBegin( GL_LINES );
      glVertex3f( -m_Range,  m_Range, 0.0 );
      glVertex3f(  m_Range,  m_Range, 0.0 );
      glVertex3f( -m_Range, -m_Range, 0.0 );
      glVertex3f(  m_Range, -m_Range, 0.0 );
      glVertex3f( -m_Range,  m_Range, 0.0 );
      glVertex3f( -m_Range, -m_Range, 0.0 );
      glVertex3f(  m_Range,  m_Range, 0.0 );
      glVertex3f(  m_Range, -m_Range, 0.0 );
      glEnd();
   }

   //*** Height Grid
   if( m_HeightGridEnabled )
   {
      glPushMatrix();
      glRotatef( 90.0, 1.0, 0.0, 0.0 );
      for( double h = m_HeightGridDistance; h <= m_HeightGridMaxHeight; h += m_HeightGridDistance )
      {
         glBegin( GL_LINES );
         glVertex3f( 0.0, h, 0.0 );
         glVertex3d( m_Range * 0.025, h, 0.0 );
         glEnd();
         renderText(
            QString( "%1m" ).arg( h ),
            m_Range * 0.05, h, 0.0,
            150.0, 15.0,
            "Arial", 20 );
      }
      glPopMatrix();
   }

   foreach( RveGLSprite *pSprite, m_GisSprites )
   {
      pSprite->projectTo2D();
   }

   glPointSize( 10.0 );
   glEnable( GL_POINT_SMOOTH );
   glBegin( GL_POINTS );
   foreach( RveGisData *pGisData, m_GisSprites.keys() )
   {
      foreach( RveGLSprite *pSprite, m_GisSprites.values( pGisData ) )
      {
         glColor3f( pGisData->color().redF(), pGisData->color().greenF(), pGisData->color().blueF() );
         glVertex3f( pSprite->getX(), pSprite->getY(), pSprite->getZ() );
      }
   }
   glEnd();
   glColor3f( 1.0, 1.0, 1.0 );

   m_pGLWidget->enter2DMode();
   foreach( RveGLSprite *pSprite, m_GisSprites )
   {
      pSprite->paint();
   }
   m_pGLWidget->leave2DMode();
}


void RveMap::drawArrow( double s ) const
{
   double arrow[6][3] =
   {
         { 0.0, 0.0, 0.0 },
         { 0.0, s,   0.0 },

         { 0.0,      s,       0.0 },
         { -0.5 * s, 0.5 * s, 0.0 },

         { 0.0, s, 0.0 },
         { 0.5 * s, 0.5 * s, 0.0 }
   };

   glBegin( GL_LINES );
   for( int i = 0; i < 6; i++ )
   {
      glVertex3f( arrow[i][0], arrow[i][1], arrow[i][2] );
   }
   glEnd();
}


void RveMap::renderText( const QString &text,
   double xPos, double yPos, double zPos,
   double xScale, double yScale,
   const QString &font, int fontSize )
{
   QPainterPath path;
   path.addText( QPointF( 0, 0 ), QFont( font, fontSize ), text );
   QList<QPolygonF> poly = path.toSubpathPolygons();

   for( QList<QPolygonF>::iterator i = poly.begin(); i != poly.end(); i++ )
   {
      glBegin( GL_LINE_LOOP );
      for(  QPolygonF::iterator p = (*i).begin(); p != i->end(); p++ )
      {
        glVertex3f( p->rx() * xScale + xPos, -p->ry() * yScale + yPos, zPos );
      }
      glEnd();
   }
}


void RveMap::calculate()
{
   if( !m_Initialized )
   {
      initializeGLFunctions();
   }

   m_Vertices.clear();
   m_Indices.clear();

   if( m_GLIndices >= 0 )
   {
      glDeleteBuffers( 1, &m_GLIndices );
   }

   if( m_GLVertices >= 0 )
   {
      glDeleteBuffers( 1, &m_GLVertices );
   }

   m_GLIndices = -1;
   m_GLVertices = -1;

   if( m_Lon == -DBL_MAX || m_Lat == -DBL_MAX )
      return;

   for( int y = 0; y < m_Precision; y++ )
   {
      double yofs_m = ( ( (double)y * m_Range * 2.0 ) / ( (double)( m_Precision - 1 ) ) ) - m_Range;
      for( int x = 0; x < m_Precision; x++ )
      {
         double xofs_m = ( ( (double)x * m_Range * 2.0 ) / ( (double)( m_Precision - 1 ) ) ) - m_Range;
         double dist = sqrt( xofs_m * xofs_m + yofs_m * yofs_m );
         qint16 h = 0;
         
         if( m_OromapEnabled )
         {
            h = height( xofs_m, -yofs_m );
         }
         double zofs_m = (double)h * 1.0;
         RveModel::Vertex v;
         v.point.x = xofs_m;
         v.point.y = yofs_m;
         v.point.z = zofs_m;
         QColor c = color( h );

         v.color.r = ( (double)c.red()   / 255.0 ) * 0.5;
         v.color.g = ( (double)c.green() / 255.0 ) * 0.5;
         v.color.b = ( (double)c.blue()  / 255.0 ) * 0.5;

         if( h < 0 )
            h = 0;

         v.color.a = m_OromapEnabled ? 1.0 : 0.0;

         if( m_RangeRingEnabled )
         {
            if( fabs( fmod( dist, m_RangeRingDistance ) ) < m_RangeRingThickness )
            {
               v.color.r = v.color.g = v.color.b = 1.0;
               v.color.a = 1.0;
            }
         }

         v.normal.x = 0.0;
         v.normal.y = 0.0;
         v.normal.z = 1.0;
         m_Vertices.append( v );
      }
   }

   foreach( RveGisData *pGisData, m_Gis )
   {
      pGisData->calculate( m_ProjPnt, range(), m_Vertices, m_Precision );
   }

   int n = 0;

   for( int y = 0; y < m_Precision - 1; y++ )
   {
      for( int x = 0; x < m_Precision - 1; x++ )
      {
         if( m_Vertices[( m_Precision * y ) + x].color.a > 0.0 )
         {
            m_Indices.append( ( ( y + 1 ) * m_Precision ) + ( x + 1 ) );
            m_Indices.append( ( ( y + 0 ) * m_Precision ) + ( x + 1 ) );
            m_Indices.append( ( ( y + 0 ) * m_Precision ) + ( x + 0 ) );

            m_Indices.append( ( ( y + 1 ) * m_Precision ) + ( x + 0 ) );
            m_Indices.append( ( ( y + 1 ) * m_Precision ) + ( x + 1 ) );
            m_Indices.append( ( ( y + 0 ) * m_Precision ) + ( x + 0 ) );
            n++;
         }
      }
   }

   glGenBuffers( 1, &m_GLIndices );
   glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, m_GLIndices );
   glBufferData( GL_ELEMENT_ARRAY_BUFFER,
                  m_Indices.size() * sizeof( int ),
                  m_Indices.data(),
                  GL_STATIC_DRAW );
   glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 );

   glGenBuffers( 1, &m_GLVertices );
   glBindBuffer( GL_ARRAY_BUFFER, m_GLVertices );
   glBufferData( GL_ARRAY_BUFFER,
                  m_Vertices.size() * sizeof( RveModel::Vertex ),
                  m_Vertices.data(),
                  GL_STATIC_DRAW );
   glBindBuffer( GL_ARRAY_BUFFER, 0 );
   
   buildGisSprites();
}


void RveMap::clearGisSprites()
{
   foreach( RveGLSprite *pSprite, m_GisSprites )
   {
      delete pSprite;
   }

   m_GisSprites.clear();
}


void RveMap::buildGisSprites()
{
   clearGisSprites();

   foreach( RveGisData *pGisData, m_Gis )
   {
      if( pGisData->isEnabled() )
      {
         const RveShpFile *pShpFile = pGisData->shpFile();
         const RveDbfFile *pDbfFile = pGisData->dbfFile();

         if( pShpFile && pDbfFile )
         {
            if( pShpFile->type() == RveShpFile::TYPE_POINT &&
                pShpFile->numShapes() == pDbfFile->numRecords() )
            {
               QSet<QString> types;
               for( int i = 0; i < pShpFile->numShapes(); i++ )
               {
                  const RveShp *pShape = pShpFile->shape( i );
                  const RveDbfRecord *pRecord = pDbfFile->record( i );

                  if( pShape->type() == RveShp::TYPE_POINT )
                  {
                     QVariant label = pRecord->value( pGisData->label(), false );

                     if( pGisData->valueFiltered( i ) )
                     {
                        const RveShpPoint *pPoint = (const RveShpPoint *)pShape;
                        QString sLabel = label.toString();
                        double lon = pPoint->getX();
                        double lat = pPoint->getY();

                        double posXm = 0.0;
                        double posYm = 0.0;
                        m_ProjPnt.getDistance( lon, lat, posXm, posYm );
                        posYm = -posYm;
                        double posZm = height( posXm, -posYm );
                        posZm += 100.0;
                        if( posXm <= m_Range && posXm >= -m_Range &&
                              posYm <= m_Range && posYm >= -m_Range )
                        {
                           RveGLSprite *pSprite = RveGLSprite::createText( m_pGLWidget, sLabel, pGisData->font(), pGisData->color() );
                           pSprite->setPosition( posXm, posYm, posZm );
                           pSprite->setHandle( 0.5, 0.0 );
                           m_GisSprites.insert( pGisData, pSprite );
                        }
                     }
                  }
               }
            }
         }
      }
   }
}


double RveMap::range() const
{
   return( m_Range );
}


bool RveMap::getDistance( double lon, double lat,
                       double &ew_m, double &ns_m )
{
   return( m_ProjPnt.getDistance( lon, lat, ew_m, ns_m ) );
}


qint16 RveMap::height( double ew_m, double ns_m )
{
   double new_lon;
   double new_lat;

   if( !m_OromapEnabled )
   {
      return( 0 );
   }

   if( m_ProjPnt.getCoordinates( ew_m, ns_m, new_lon, new_lat ) )
   {
      return( m_pDem->height( new_lon, new_lat, true ) );
   } else
   {
      return( -9999 );
   }
}
