/*
 *  sweepLine.h
 *  Bentley
 *
 *  Created by Chema on 7/14/10.
 *  Copyright 2010 __MyCompanyName__. All rights reserved.
 *
 */


#include <functional>
#include <vector>
#include <list>
#include <set>
#include "vec.h"
#include "font.h"
#include "segment.h"

#ifndef sweepLine_H
#define sweepLine_H

struct Segment;

    
struct SL {
    
    struct Interx {
        typedef std::set<Interx> set;
        
        DReal2 p_;
        Event::queue::iterator eitr_;
        Segment* a_;
        Segment* b_;
        
        Interx(Segment* a, Segment* b, const DReal2& p) :
            a_((*a).index_<(*b).index_?a:b),
            b_((*b).index_<(*a).index_?a:b),
            p_(p)
        {;}

        bool operator<(const Interx& ref) const {
            bool ret=false;
            int ai = (*a_).index_;
            int bi = (*b_).index_;
            int rai = (*ref.a_).index_;
            int rbi = (*ref.b_).index_;
            // test the min first
            if (ai<rai) {
                ret=true;
            }
            else if (ai==rai) {
                if (bi<rbi) {
                    ret=true;
                }
            }
            return ret;
        }         
    };
    
    struct Span {
        typedef std::vector<Span> vector;
        DReal2 l_;
        DReal2 r_;
        const Triangle* tri_;
        
        Span (const Triangle* tri, const DReal2& l) :
            l_(l),
            r_(DReal2(0.)),
            tri_(tri)
            {;}
    };
    
    Segment::tree tree_;
    Event::queue events_;
    Interx::set interxs_;
    Span::vector spans_;
    
    // debug
    int cc_;
    float average0_,average1_,average2_;


    public:
    SL() {;}
    ~SL(void) {;}

    void clear() {
        tree_.clear();      
        interxs_.clear();
        spans_.clear();
        events_.clear();
    }

    void init(Triangle::list& tris);
    void run(int& debug, Font& font);

private:
    std::pair<Segment::tree::iterator,bool> addSegment(Segment* s);
    void removeSegment(Segment* s); 
    void cleanInterxEvents();
};


#endif