/*----------------------------------------------------------------------------*/
/*!
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 <QCoreApplication>
#include <QDir>
#include <QString>

#include "RveDem.h"

qint16 const RveDem::m_oceanHeightReal = 0;         /*!< real height of ocean */
qint16 const RveDem::m_oceanHeightMap = 0;      /*!< height with which ocean is coded */

/*---------------------------------------------------------------------------*/
/*!*/
/*---------------------------------------------------------------------------*/
RveDem::RveDem( QObject *parent ) :
   QObject( parent )
{
   m_prevDemKey = 0;
   m_demDir =
      ( QStringList()
        << QCoreApplication::applicationDirPath()
        << ".."
        << "dem"
        << "srtm30" ).join( QDir::separator() ) + QDir::separator();
   m_pPrevBufferCache = NULL;
}


/*---------------------------------------------------------------------------*/
/*!*/
/*---------------------------------------------------------------------------*/
RveDem::~RveDem()
{
}


QString RveDem::getFileName( int iLon, int iLat ) const
{
   return( m_demDir + QString( "%1%2%3%4.DEM" )
           .arg( iLon < 0 ? "W" : "E" )
           .arg( iLon < 0 ? -iLon : iLon, 3, 10, QChar( '0' ) )
           .arg( iLat < 0 ? "S" : "N" )
           .arg( iLat < 0 ? -iLat : iLat, 2, 10, QChar( '0' ) ) );
}


bool RveDem::readDem( const QString& demFile, QVector<qint16>& fileBuffer )
{
   int offset = 0;
   if( demFile.isEmpty() )
   {
      return( false );
   }

   QFile file( demFile );
   if ( !file.open( QIODevice::ReadOnly ) )
   {
     return( false );
   }

   int sz = fileBuffer.size();
   QByteArray ba( offset + 2 * sz, 0 );
   qint64 bytesRead = file.read( ba.data(), ba.size()  );
   file.close();

   if ( ( bytesRead < 0 ) || ( bytesRead < (qint64) ba.size() ) )
   {
     return( false );
   }

   int j = 0;
   for( int i = 0; i < sz; ++i, j+= 2 )
   {
      quint8 i1 = ba[j];
      quint8 i2 = ba[j + 1];
      fileBuffer[i] = ( i1 << 8 ) | i2;
/*      int i1 = ba[ j ];
      int i2 = ba[ j + 1 ];
      if( i2 < 0 )  i2 += 256;
      fileBuffer[ i ] = 256 * i1 + i2;*/
   }

   return( true );
}


/*----------------------------------------------------------------------------*/
/*!
*/
/*----------------------------------------------------------------------------*/
const qint16 *RveDem::getFileBuffer( int ofKey, int iLon, int iLat )
{
  if( m_demFileCache.contains( ofKey ) )
  {
    const QVector<qint16> *pDataArr = m_demFileCache[ ofKey ];
    return ( pDataArr ? pDataArr->data() : NULL );
  }

  // read file into buffer
  int bufSize = 4800 * 6000;

  QVector<qint16> fileBuffer( bufSize );
  if( readDem( getFileName( iLon, iLat ), fileBuffer ) )
  {
    m_demFileCache[ ofKey ] = new QVector<qint16>( fileBuffer );
  }
  else
  {
    // even if NULL put in the cache not to load it again
    m_demFileCache[ ofKey ] = NULL;    
  }

  return( getFileBuffer( ofKey, iLon, iLat ) );
}


qint16 RveDem::height( double lon, double lat, bool realHeight )
{
   int iLon = ( ( (int) floor( ( lon + 20 ) / 40.0 ) ) * 40 ) - 20;
   int iLat = ( ( (int) floor( ( lat + 10 ) / 50.0 ) ) * 50 ) + 40;
   int curDemKey = ( ( iLon << 10 ) + iLat );

   const qint16* fileBuffer = NULL;
   if( curDemKey == m_prevDemKey )
   {
      fileBuffer = m_pPrevBufferCache;
   }
   else
   {
      fileBuffer = getFileBuffer( curDemKey, iLon, iLat );
      m_pPrevBufferCache = fileBuffer;
      m_prevDemKey = curDemKey;
   }

   if( fileBuffer == NULL )  return( realHeight ? m_oceanHeightReal : m_oceanHeightMap );

   // lon/lat differences to lower-left map border, in "pixels"
   double dLon1 = (double) 4800.0 * ( ( lon - ( double ) iLon ) / 40.0 );
   double dLat1 = (double) 6000.0 * ( ( ( double ) iLat - lat ) / 50.0 );

   // next neighbor
   int iLon1 = (int) dLon1;
   int iLat1 = (int) dLat1;
   qint16 iData = fileBuffer[ iLon1 + 4800 * iLat1 ];
   bool isOcean = false;
   if( iData == m_oceanHeightMap )
   {
      // Ocean surface
      iData = m_oceanHeightReal;
      isOcean = true;
   }

   // calculate final height; take care for ocean
   qint16 finalHeight = iData;
   if( finalHeight == m_oceanHeightReal )
   {
      // no Ocean in land side
      if( ! isOcean )          finalHeight = m_oceanHeightReal + 1;
      else if( ! realHeight )  finalHeight = m_oceanHeightMap;
   }
   return( finalHeight );
}
