/******************************** LICENSE ********************************

 Copyright 2007 European Centre for Medium-Range Weather Forecasts (ECMWF)

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at 

    http://www.apache.org/licenses/LICENSE-2.0

 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.

 ******************************** LICENSE ********************************/

/*! \file NetcdfGeoMatrixInterpretor.cc
    \brief Implementation of the Template class NetcdfGeoMatrixInterpretor.
    
    Magics Team - ECMWF 2004
    
    Started: Tue 17-Feb-2004
    
    Changes:
    
*/

#include "NetcdfGeoMatrixInterpretor.h"
#include "Factory.h"
#include "Netcdf.h"
#include <limits>
#include "Layer.h"

using namespace magics;

NetcdfGeoMatrixInterpretor::NetcdfGeoMatrixInterpretor() 
{}


NetcdfGeoMatrixInterpretor::~NetcdfGeoMatrixInterpretor() 
{}



void NetcdfGeoMatrixInterpretor::interpretAsMatrix(Matrix** data)
{
	if ( *data ) return;
	
	matrix_ = new Matrix();
	matrix_->akimaEnabled();
	*data = matrix_;

   
	Netcdf netcdf(path_);
	double missing_value = missing(netcdf);

	// get the data ...
	try
	{
		map<string, string> first, last;
		setDimensions(dimension_, first, last);

		netcdf.get(longitude_, matrix_->columnsAxis(), first, last);
		netcdf.get(latitude_, matrix_->rowsAxis(), first, last);
		


		matrix_->missing(missing_value);

		if  ( magCompare(primary_index_, "latitude") ) {
			// WE reserve the matrix_ since we are used to lat/lon matrix_!
			vector<double> data;
			netcdf.get(field_, data, first, last);
			int columns =  matrix_->columnsAxis().size();
			int rows =  matrix_->rowsAxis().size();
 
		    for (int lon = 0; lon < columns; lon++)
			     for (int lat = 0; lat < rows; lat++) {
			    	matrix_->push_back(data[lon + lat*rows]);
			     }
		}
		else 	{
			vector<double> data;	
			netcdf.get(field_, data, first, last);
			int i = 0;
			for (vector<double>::iterator d = data.begin(); d != data.end(); ++d ) {
				if ( !isnan(*d) ) {
					matrix_->push_back(*d);
				}
				else 
					matrix_->push_back(missing_value);
			   i++;
			}
		}


		matrix_->multiply(scaling_);
		matrix_->plus(offset_);
        

        
	        matrix_->setMapsAxis();
        

	}
	catch (MagicsException& e)
	{
		MagLog::error() << e << "\n";
	}
}

/*
 Class information are given to the output-stream.
*/		
void NetcdfGeoMatrixInterpretor::print(ostream& out)  const
{
	out << "NetcdfGeoMatrixInterpretor[";
	NetcdfInterpretor::print(out);
	NetcdfGeoMatrixInterpretorAttributes::print(out);
	out << "]";
}

void NetcdfGeoMatrixInterpretor::interpretAsPoints(PointsList<GeoPoint>& list) 
{
	Netcdf netcdf(path_);
	
	// get the data ...
	try
	{
		vector<double> latitudes;
		vector<double> longitudes;
		vector<double> values;
		map<string, string> first, last;
		setDimensions(dimension_, first, last);
		
		netcdf.get(field_, values, first, last);
		netcdf.get(longitude_, longitudes, first, last);
		netcdf.get(latitude_, latitudes, first, last);
		unsigned int val = 0;
		
		for (unsigned int  lat  =0 ; lat < latitudes.size(); lat+=latitude_sample_) {
			for ( unsigned int lon = 0; lon < longitudes.size(); lon+=longitude_sample_) {
				val = (lat* longitudes.size() + lon);
				if (val >= values.size() ) return;
				if ( values[val] < suppress_below_ ) continue;
				if ( values[val] > suppress_above_ ) continue;
				if ( same(values[val], missing(netcdf) ) ) continue;
				list.push_back(GeoPoint(longitudes[lon],latitudes[lat],values[val]));
			}
		}
 		MagLog::dev()<< "everything ok" << endl;
	}
	catch (MagicsException& e)
	{
		MagLog::error() << e << "\n";
	}
}

void NetcdfGeoMatrixInterpretor::visit(MetaDataCollector&)
{
}

void NetcdfGeoMatrixInterpretor::visit(ValuesCollector& points)
{	
	points.setCollected(true);
	
  	assert(matrix_); 
	//const Transformation& transformation = points.transformation();
	for (ValuesCollector::iterator point =  points.begin(); point != points.end(); ++point) {
		//PaperPoint pp((*point).x(), (*point).y());
		UserPoint geo((*point).x(), (*point).y());
		//transformation.revert(pp, geo);	
		(*point).push_back(ValuesCollectorData(geo.x(),geo.y(),matrix_->interpolate(geo.y(), geo.x()),-1.));
	}
}
