/***************************** LICENSE START ***********************************

 Copyright 2014 ECMWF and INPE. This software is distributed under the terms
 of the Apache License version 2.0. In applying this license, ECMWF does not
 waive the privileges and immunities granted to it by virtue of its status as
 an Intergovernmental Organization or submit itself to any jurisdiction.

 ***************************** LICENSE END *************************************/

#include "FolderSearchData.h"

#include <algorithm> 
#include "IconObject.h"

FolderSearchData::FolderSearchData() : 
   observer_(0),
   owner_(0),
   current_(0)
{
}  

void FolderSearchData::setObserver(FolderSearchDataObserver *obs)
{
  	observer_=obs;
}

void FolderSearchData::clear()
{
 	name_.clear();
	type_.clear();
	clearMatch(); 
}  

void FolderSearchData::setSearchTerm(const std::string& name,const std::string& type)
{
  	name_=name;
	type_=type;
	clearMatch();
} 

bool FolderSearchData::isSet()
{
  	return !name_.empty() || !type_.empty();
}

bool FolderSearchData::hasMatch()
{
  	return matchVec_.size() > 0; 
}

void FolderSearchData::clearMatch()
{
  	matchVec_.clear();
	current_=0;
}	

bool FolderSearchData::match(IconObject* obj)
{
  	if(matchVec_.size() > 0)
	{
	  	std::vector<IconObject*>::iterator it=std::find(matchVec_.begin(),matchVec_.end(),obj);
		if(it != matchVec_.end())
		  	return true;
		else
		  	return false;
	}
	
	return false;
}	

void FolderSearchData::load(IconObject* obj)
{
	if(!name_.empty() || !type_.empty())
	{
	  	if(obj->match(name_,type_))
		  	matchVec_.push_back(obj);
	}	
}  
  
void FolderSearchData::matchChanged() 
{
  	if(observer_)
	  	observer_->matchChanged();
}	

void  FolderSearchData::resetCurrent()
{
  	current_=0;
}

IconObject* FolderSearchData::next()
{
  	if(matchVec_.size() == 0)
	  	return 0;
  	
  	current_+=1;
	
	if(current_ >= static_cast<int>(matchVec_.size()))
		current_=0;
	if(current_ <0)
	  	current_=matchVec_.size()-1;
	
	if(current_ >=0 && current_ <static_cast<int>(matchVec_.size()))
		return matchVec_.at(current_);
	
	return 0;
}

IconObject* FolderSearchData::prev()
{
  	if(matchVec_.size() == 0)
	  	return 0;
	
	current_-=1;
	
	if(current_ <0)
	  	current_=static_cast<int>(matchVec_.size())-1;
	if(current_ >= static_cast<int>(matchVec_.size()))
		current_=0;
	
	if(current_ >=0 && current_ < static_cast<int>(matchVec_.size()))
		return matchVec_.at(current_);
	
	return 0;
}

IconObject* FolderSearchData::first()
{
	if(matchVec_.size() == 0)
	  	return 0;
	return matchVec_.at(0);	
}
	

