/******************************** 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 InputMatrix.h
    \brief Implementation of the Template class InputMatrix.
    
    Magics Team - ECMWF 2005
    
    Started: Fri 16-Sep-2005
    
    Changes:
    
*/


#include "Transformation.h"
#include "Timer.h"

using namespace magics;

template <class P>
InputMatrix<P>::InputMatrix():  matrix_(0), u_(0), v_(0), speed_(0), direction_(0) 
{
	Timer timer("InputMatrix<P>", "Loading data");
	filter(field_);
	filter(u_component_);
	filter(v_component_);
	filter(wind_speed_);
	filter(wind_direction_);
	if ( !field_.empty()) 
		matrix_ = (*organization_).interpret(&field_, *this); 
	if ( !u_component_.empty()) 
		u_ = (*organization_).interpret(&u_component_, *this); 
	if ( !v_component_.empty()) 
		v_ = (*organization_).interpret(&v_component_, *this);	
	if ( !wind_speed_.empty()) 
		speed_ = (*organization_).interpret(&wind_speed_, *this);	
	if ( !wind_direction_.empty()) 
		direction_ = (*organization_).interpret(&wind_direction_, *this);	
}


template <class P>
InputMatrix<P>::~InputMatrix() 
{
}

/*!
 Class information are given to the output-stream.
*/
template <class P>
void InputMatrix<P>::print(ostream& out)  const
{
	out << "InputMatrix[";
	out << field_;
	out << "]";
}

template <class P>
MatrixHandler<P>& InputMatrix<P>::matrix() 
{
	Timer timer("InputMatrix<P>", "Getting data");
	if (simple_field_) 
		matrix_ = (*organization_).interpret(&field_, *this); 
	this->matrixHandlers_.push_back(new MatrixHandler<P>(*matrix_));         
	return *(this->matrixHandlers_.back()); 
}


template <class P>
void InputMatrix<P>::filter(Matrix& data)
{
	for ( unsigned int i = 0; i < data.size(); i++ )
		if ( data[i] <= suppress_below_ || data[i] >= suppress_above_ ) 
			data[i] = data.missing();
}


template <class P>
void  InputMatrix<P>::release()
{
	 if ( matrix_ )
		 matrix_->release();

	 if ( u_ )
		 u_->release();

	 if ( v_ )
		 v_->release();

	 if ( speed_ )
	 	speed_->release();

	 if ( direction_ )
		direction_->release();
}

template <class P>
pair<double, double> InputMatrix<P>::sd2uv(double s, double d)
{
	double a = 90 - (d);
	double pi = 3.14/180.;
	a *= pi;
    return make_pair(s * -1 * cos(a), s*-1* sin(a));
}


template <class P>
MatrixHandler<P>& InputMatrix<P>::xComponent() 
{
	if ( !u_ )
		prepareComponents();

	this->matrixHandlers_.push_back(new MatrixHandler<P>(*u_));
	return *(this->matrixHandlers_.back());
}


template <class P>
void InputMatrix<P>::prepareComponents()
{
		Matrix u, v;
		// We calculate the u_component_ using the speed and direction...
		vector<double>::const_iterator speed = speed_->begin();
		vector<double>::const_iterator angle = direction_->begin();

		while ( speed != speed_->end() && angle != direction_->end() )
		{
			if ( *speed == speed_->missing() || *angle == direction_->missing() ) {
					 u.push_back(direction_->missing());
					 v.push_back(direction_->missing());
			}
			else if ( *speed == 0 && *angle == 0   ) {
					u.push_back(direction_->missing());
					v.push_back(direction_->missing());
			}
			else {
				pair<double, double> uv = sd2uv(*speed, *angle);
				u.push_back(uv.first);
				v.push_back(uv.second);
			}
			speed++;
			angle++;
		}
		u_ = speed_;
		v_ = direction_;
		u_->clear();
		v_->clear();
		std::copy(u.begin(), u.end(), back_inserter(*u_));
		std::copy(v.begin(), v.end(), back_inserter(*v_));
}


template <class P>
MatrixHandler<P>& InputMatrix<P>::yComponent()
{
	if ( !v_ )
		prepareComponents();
	Data<P>::matrixHandlers_.push_back(new MatrixHandler<P>(*v_));         
	return *(this->matrixHandlers_.back()); 
}

template <class P>
PointsHandler<P>& InputMatrix<P>::points(const Transformation& transformation)
{
		this->pointsHandlers_.push_back(new BoxPointsHandler<P>(this->matrix(), transformation)); 
		return *(this->pointsHandlers_.back());
}

template <class P>
void InputMatrix<P>::customisedPoints(const BasicThinningMethod& thinning, const Transformation& transformation, const std::set<string>&, CustomisedPointsList& points)
{
	vector<P> thinx;
	vector<P> thiny;

	int factor = thinning.factor();
	MatrixHandler<P> inx = xComponent();
	MatrixHandler<P> iny = yComponent();
	transformation.thin(inx, factor, factor, thinx);

	transformation.thin(iny, factor, factor, thiny);

	typename vector<P>::const_iterator x = thinx.begin();
	typename vector<P>::const_iterator y = thiny.begin();

	if (thinx.empty()) return;
	while (x->value() == inx.missing() || y->value() == iny.missing())
	{
		++x;
		++y;
		if (x == thinx.end() || y == thiny.end()) 
			return;
	}
	CustomisedPoint *point = new CustomisedPoint(x->x(), x->y(), "");
	point->insert(make_pair("x_component", x->value()));
	point->insert(make_pair("y_component", y->value()));
	points.push_back(point);

//	double lastx = x->x();
//	double lasty = x->x();
	x++;
	y++;
	while ( x != thinx.end() && y != thiny.end() )
	{
		if ( x->value() != inx.missing() &&  y->value() != iny.missing() )
		{
			CustomisedPoint *point = new CustomisedPoint(x->x(), x->y(), "");
			point->insert(make_pair("x_component", x->value()));
			point->insert(make_pair("y_component", y->value()));
			points.push_back(point);

		}
//		lastx = x->x();
		x++;
		y++;
	} 
}
