/***************************************************************************
 *   Copyright (C) 2005 by Thierry CHARLES   *
 *   thierry@les-charles.net   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

#include "tselection.h"

void TSelection::setBegin(TPoint pt)
{
    if(pt != this->begin)
    {
        this->fireClearSelection();
        this->begin = pt;
        this->fireSelectionChanged();
    }
}

void TSelection::setEnd(TPoint pt)
{
    if(pt != this->end)
    {
        this->fireClearSelection();
        this->end = pt;
        this->fireSelectionChanged();
    }
}

void TSelection::fireClearSelection()
{
    TSelectionListenersList::iterator itB = this->listeners.begin();
    TSelectionListenersList::iterator itE = this->listeners.end();

    while(itB != itE)
    {
        (*itB)->clearSelection(this);
        itB++;
    }
}

void TSelection::fireSelectionChanged()
{
    TSelectionListenersList::iterator itB = this->listeners.begin();
    TSelectionListenersList::iterator itE = this->listeners.end();

    while(itB != itE)
    {
        (*itB)->selectionChanged(this);
        itB++;
    }
}

bool TSelection::addSelectionListener(TSelectionListener * sl)
{
    return this->listeners.insert(sl).second;
}

bool TSelection::removeSelectionListener(TSelectionListener * sl)
{
    return this->listeners.erase(sl) != 0;
}

void TSelection::clear()
{
    this->fireClearSelection();
    this->begin.x = -1;
    this->begin.y = -1;
    this->end.x = -1;
    this->end.y = -1;
}

std::ostream & operator << (std::ostream &out, const TSelection &sel)
{
    out << "{" << sel.getBegin() << ";" << sel.getEnd() << "}";
    return out;
}
