/******************************** 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 Polyline.h
    \brief Definition of polyline graphics class.
    \author Meteorological Visualisation Section, ECMWF

    Started: Jan 2004

*/
#ifndef Polyline_H
#define Polyline_H

#include "magics.h"

#include "BasicGraphicsObject.h"
#include "BaseDriver.h"
#include "VectorOfPointers.h"
#include "Label.h"

namespace magics {

struct ShadingProperties
{
    ShadingProperties() 
    {}
    virtual ~ShadingProperties() {}
    virtual ShadingProperties* clone() = 0;
    virtual void draw(const BaseDriver& driver) const = 0;
   
    virtual void print(ostream& out) const
    {
       out << "ShadingProperties[";
       out << "]";
    }
    friend ostream& operator<<(ostream& s,const ShadingProperties& p)
		{ p.print(s); return s; }
};

struct FillShadingProperties : public ShadingProperties
{
    FillShadingProperties() {}
    ~FillShadingProperties() {}
    ShadingProperties* clone()
    {	
        FillShadingProperties* shading = new FillShadingProperties();
        return shading;
    }
    void draw(const BaseDriver& driver) const { driver.shade(*this); }
    void print(ostream& out) const
    {
       out << "FillShadingProperties[";
       out << "]";
   }
};


struct DotShadingProperties : public ShadingProperties
{
    DotShadingProperties() : angle_(45), size_(0.02), density_(25){}
    ~DotShadingProperties() {}
    void draw(const BaseDriver& driver) const { driver.shade(*this);}
    double angle_;
    double size_;
    double density_;
    ShadingProperties* clone()
    {
        DotShadingProperties* shading = new DotShadingProperties();
        shading->angle_ = angle_;
        shading->size_ = size_;
        shading->density_ = density_;
        return shading;
    }

    void print(ostream& out) const
    {
       out << "DotShadingProperties["   
           << ", angle=" << angle_
           << ", size=" << size_
           << ", density=" << density_
           << "]";
   }
};

struct HatchShadingProperties : public ShadingProperties 
{
    HatchShadingProperties() : index_(0), thickness_(1), density_(18) {}
    ~HatchShadingProperties() {}
    void draw(const BaseDriver& driver) const {driver.shade(*this);} 
    int index_;
    int thickness_;
    double density_;
    ShadingProperties* clone() {
        HatchShadingProperties* shading = new HatchShadingProperties();
        
        shading->index_ = index_;
        shading->thickness_ = thickness_;
        shading->density_ = density_;
        return shading;
    }
    void print(ostream& out) const {
       out << "HatchShadingProperties[";
       out << ", thickness=" << thickness_;
       out << ", index=" << index_;
       out << ", density=" << density_;
       out << "]";
   }
};


class PolylineProperties : public BasicGraphicsObject 
{
public :
	PolylineProperties() :  thickness_(1), dash_length_(10), style_(M_SOLID), fill_(false), shading_(0), stroke_(true), antialiasing_(true) {}
	virtual ~PolylineProperties() { if (shading_) delete shading_; }
	
	virtual void copy(const PolylineProperties& other)
	{			
		label_       = other.label_ ;
		colour_ = other.colour_;
		thickness_ 	 = other.thickness_;
		dash_length_ = other.dash_length_;	
		style_       = other.style_;
		fill_        = other.fill_;
		antialiasing_ = other.antialiasing_;
		fill_colour_ = other.fill_colour_;
		if ( shading_ ) delete shading_;
		shading_     = other.shading_ ? other.shading_->clone() : 0;
	}
	//! Method to set the thickness of a drawn line.
	void setThickness(int t){thickness_ = t;}
	//! Method to get the thickness of a drawn line.
	int getThickness() const {return thickness_;}

	//! Method to set the length of dashes in the line.
	void setDashLength(int dl){dash_length_ = dl;}
	//! Method to get the length of dashes in the line.
	int getDashLength() const {return dash_length_;}

	//! Method to set the style for the drawn line.
	void  setLineStyle(LineStyle ls){style_ = ls;}
	//! Method to get the style for the drawn line.
	LineStyle getLineStyle() const {return style_;}
	
	//! Method to set the colour for the drawn line.
	void  setColour(const Colour& colour){colour_ = colour;}
	//! Method to get the colour for the drawn line.
	const Colour& getColour() const {return colour_;}
	
	//! Method to set filling.
	void  setFilled(bool fill){fill_ = fill;}
	//! Method to get the style for the drawn line.
	bool isFilled() const {return fill_;}
	
	void setFillColour(Colour col){  fill_colour_ = col;}
	Colour getFillColour() const {return fill_colour_;}
	
	void setLabel(const Label& label){  label_ = label;}
	const Label& getLabel() const {return label_;}
	void setAntiAliasing(bool antialiasing){ antialiasing_ = antialiasing; }
	bool getAntiAliasing() const {return antialiasing_;}
	
	void setStroke(bool stroke){ stroke_ = stroke; }
	bool isStroked() const {return stroke_;}

	void setShading(ShadingProperties* shading)
	{ 
		if ( shading_) delete shading_; 
		shading_ = shading; 
	}
	
	ShadingProperties* getShading() const { return shading_; }

protected:
	int			thickness_;
	int			dash_length_;	
	LineStyle		style_;
	bool			fill_;
	Colour			fill_colour_;
	ShadingProperties*	shading_; 
	Label                   label_;
	Colour                  colour_;
	bool                    stroke_;
	bool                    antialiasing_;
};


class Polyline: public deque<PaperPoint>, public PolylineProperties
{
public:
    
	Polyline();
	virtual ~Polyline();
	
	bool reproject(BasicGraphicsObjectContainer& out) const;
	void redisplay(const BaseDriver& driver) const;
	bool land() { return land_; }
	void land(bool land) { land_ = land; }

	void push_back(const PaperPoint& point)
	{	
		if (maxY_ < point.y_) maxY_ = point.y_;
		if (minY_ > point.y_) minY_ = point.y_;
		if (maxX_ < point.x_) maxX_ = point.x_;
		if (minX_ > point.x_) minX_ = point.x_;
		deque<PaperPoint>::push_back(point);
	} 

	void push_front(const PaperPoint& point)
	{	
		if (maxY_ < point.y_) maxY_ = point.y_;
		if (minY_ > point.y_) minY_ = point.y_;
		if (maxX_ < point.x_) maxX_ = point.x_;
		if (minX_ > point.x_) minX_ = point.x_;
		deque<PaperPoint>::push_front(point);
	} 
	
	// Is the poyline included in the "other" polyline"
	bool in(const Polyline& other)
	{
		if ( other.getMaxX() < getMaxX() ) return false;
  		if ( other.getMaxY() < getMaxY() ) return false;
 		if ( other.getMinX() > getMinX() ) return false;
  		if ( other.getMinY() > getMinY() ) return false;

  		return true;
	}
// Is the poyline outside the "other" polyline"
	bool out(const Polyline& other)
	{
		return !in(other);
	}


    /*
        calculate_bounding_box
        Ideally should not exist, because all operations that add points
        should set the bounds. But there are places where this does not occur
        (ie, anywhere that a std algorithm operator is used), so we sometimes
        have to use this function. It would probably be more efficient, however,
        to go always go through operators.
    */

    void calculate_bounding_box (void)
    {
        double fMinX = INT_MAX, fMinY = INT_MAX, fMaxX = INT_MIN, fMaxY = INT_MIN;

        for (Polyline::const_iterator point = this->begin(); point != this->end(); ++point)
        {
            if (point->x_ < fMinX) fMinX = point->x_;
            if (point->y_ < fMinY) fMinY = point->y_;
            if (point->x_ > fMaxX) fMaxX = point->x_;
            if (point->y_ > fMaxY) fMaxY = point->y_;
        }

        minX_ = fMinX;
        minY_ = fMinY;
        maxX_ = fMaxX;
        maxY_ = fMaxY;

        bounding_box_is_current_ = true;
    }


#ifdef MAGICS_DEBUG_X

    /*
        check_bounding_box
        Determines whether the polygon's bounding box is correct. This should only really
        be used for debugging purposes.
    */

    bool check_bounding_box (void) const
    {
        double fMinX = INT_MAX, fMinY = INT_MAX, fMaxX = INT_MIN, fMaxY = INT_MIN;

        for (Polyline::const_iterator point = this->begin(); point != this->end(); ++point)
        {
            if (point->x_ < fMinX) fMinX = point->x_;
            if (point->y_ < fMinY) fMinY = point->y_;
            if (point->x_ > fMaxX) fMaxX = point->x_;
            if (point->y_ > fMaxY) fMaxY = point->y_;
        }

        if (fMinX != getMinX() ||
            fMaxX != getMaxX() ||
            fMinY != getMinY() ||
            fMaxY != getMaxY())
        {
            return false;  
        }
        
        else
        {
            return true;
        }
    }
    
#endif

	/*!
	  Counts checks if a given point is in the Polyline
	  This method can be used to see if a point at x_in and y_in
	  lies inside a CLOSED Polyline. If counts is odd the point
	  should lie inside.
	*/
	bool inside(const float x_in,const float y_in) const
	{
		if ( x_in < minX_ ) return false;
		if ( x_in > maxX_ ) return false;
		if ( y_in < minY_ ) return false;
		if ( y_in > maxY_ ) return false;
		return true;
		/*
		int counts = 0;
		unsigned int s = this->size();
		for(unsigned int j=0;j<s-2;j++)
		{
		  if( ((*this)[j].y()>y_in) && ((*this)[j+1].y()>y_in) )
		  { 
			const double x1 = (*this)[j].x();
			const double x2 = (*this)[j+1].x();
			if( ((x1>=x_in) && (x2<x_in)) || ((x1<=x_in) && (x2>x_in)) )
				counts++;
		  }
		}
		return ((counts%2)==1);
		*/
	}



	bool isClosed() const
	{ 
		if ( !this->empty() ) 
			return this->front() == this->back(); 
		return true;
	}

	bool include(const Polyline& other) const
	{
		return ( maxY_ >= other.getMaxY() &&
			 minX_ <= other.getMinX() &&
			 minY_ <= other.getMinY() &&
			 maxX_ >= other.getMaxX() && 
			 ( maxY_ != other.getMaxY() ||
			 minX_ != other.getMinX() ||
			 minY_ != other.getMinY() ||
			 maxX_ != other.getMaxX() ) );
	} 

	double getMaxY() const { return maxY_; }
	double getMinY() const { return minY_; }
    
	void setMaxY(double y) {maxY_=y;}
	void setMinY(double y) {minY_=y;}
    
	double getMaxX() const { return maxX_; }
	double getMinX() const { return minX_; }
    
	void setMaxX(double x) {maxX_=x;}
	void setMinX(double x) {minX_=x;}
	
	bool allMissing() const
	{		
	    const_iterator p = this->begin();
	    while (p != this->end() )
	    {
	    	if ( !p->missing() ) 
	    		return false;
	    	p++;
	    }
	    return true;
	}
	    	
	bool someMissing() const
	{
	    const_iterator p = this->begin();
	    while (p != this->end() )
	    {
	    	if ( p->missing() ) 
	    		return true;
	    	p++;
	    }
	    return false;
	}		 

	void setBoundingBoxCurrent(bool is_current) { bounding_box_is_current_ = is_current; }
	bool isBoundingBoxCurrent(void) const { return bounding_box_is_current_; }


	Polyline* simplify(double);
	bool lowInside() { return windingFactor() < 0; }
    
	virtual Polyline* getNew() const;

	inline double isLeft(const PaperPoint& p1, const PaperPoint& p2) const
	{
		// Return: >0 for reference is on the left of the segment
		//            =0 for reference is on the segment
		//            <0 for reference is  on the right of the segment

		return ((p2.x_ - p1.x_) * (reference_.y_ - p1.y_) - 
			(reference_.x_ - p1.x_) * (p2.y_ - p1.y_));
	}

	void reference(const PaperPoint& reference) { reference_ = reference; }
	const PaperPoint& reference() const { return reference_; }
	inline double y() const { return reference_.y_; }
	int windingFactor() const;
	void windingFactor(int factor) { winding_ = factor; }
	
	bool clockwise() { area(); return area_ < 0; }
	void makeCounterClockwise();
	void makeClockwise();
	bool inside(const Polyline&) const;
	double area(); 
	double surface() { area(); return abs(area_/2); }

	// Holes
	void newHole(const Polyline&);
	void newHole();
	void push_back_hole(const PaperPoint& point);
	typedef vector<deque<PaperPoint> > Holes;

	void hole(Holes::const_iterator, Polyline&) const;
	Holes::const_iterator beginHoles() const;
	Holes::const_iterator endHoles() const;
	void hole(Holes::const_iterator, vector<double>&, vector<double>&) const;
	unsigned int numberOfHoles() const {return holes_.size();} 
	void  clearHoles()  { holes_.clear();} 

protected:
	virtual void print(ostream&) const; 
	bool land_;

	mutable double	maxY_;
	mutable double	minY_;
	mutable	double	maxX_;
	mutable double	minX_;
	mutable int	winding_;
	mutable double	area_;
	bool            bounding_box_is_current_;
	PaperPoint      reference_;
	Holes holes_;

private: 
	Polyline(const Polyline&);
	Polyline& operator=(const Polyline&);

// -- Friends
	friend ostream& operator<<(ostream& s,const Polyline& p)
		{ p.print(s); return s; }
};


class PolylineSet : public BasicGraphicsObjectContainer
{
public:	
	PolylineSet() {}		
	~PolylineSet() { }

	void redisplay(const BaseDriver& driver) const 
		{ driver.redisplay(*this); }
protected:
	void print(ostream& out) const { out << "PolylineSet[ " << objects_.size() << " elts]\n" << endl; }

private: 
	PolylineSet(const Polyline&);
	PolylineSet& operator=(const PolylineSet&);

// -- Friends
	friend ostream& operator<<(ostream& s,const PolylineSet& p)
		{ p.print(s); return s; }
};

} // namespace magics

#endif
