package controller.client;

import controller.Search_Controller;
import controller.history.Application_Controller;
import org.sig.fw.db.corrida.dao.Client_DBAO;
import org.sig.fw.db.corrida.model.Client;
import view.client.Search_Client_View;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class Search_Client_Controller extends Search_Controller 
{
	private List<Client> clients = new ArrayList<Client>();
	
	public Search_Client_Controller(Application_Controller ctrl_application)
	{
		super(ctrl_application);
		this.vw_search = new Search_Client_View(this);
		this.vw_search.setVisible(true);
	}
	
	@Override
	public void refine(HashMap<Integer, Object> datas) 
	{
		if(vw_search == null)
			return;

		List<Integer> values = new ArrayList<Integer>();;
		
		for(Client cli : clients)
		{
			boolean company_find = true;
			boolean zipcode_find = true;
			boolean city_find = true;
			boolean public_find = true;
			boolean sfac_find = true;
			boolean factor_find = true;
			
			if(datas.get(Client_DBAO.SEARCH_COMPANY) != null)
			{
				company_find = cli.getCompany().toUpperCase().contains(((String)datas.get(Client_DBAO.SEARCH_COMPANY)).toUpperCase());
			}
			
			if(datas.get(Client_DBAO.SEARCH_ZIPCODE) != null)
			{
				zipcode_find = cli.getAddress().getZipcode().contains((String) datas.get(Client_DBAO.SEARCH_ZIPCODE));
			}
			
			if(datas.get(Client_DBAO.SEARCH_CITY) != null)
			{
				city_find = cli.getAddress().getCity().toUpperCase().contains(((String)datas.get(Client_DBAO.SEARCH_CITY)).toUpperCase());
			}
			
			if(datas.get(Client_DBAO.SEARCH_IS_PUBLIC) != null)
			{
				boolean isPublic = (boolean)datas.get(Client_DBAO.SEARCH_IS_PUBLIC);
				public_find = cli.isPublic() == isPublic;
			}
			
			if(datas.get(Client_DBAO.SEARCH_IS_FACTOR) != null)
			{
				boolean isFactor = (boolean)datas.get(Client_DBAO.SEARCH_IS_FACTOR);
				sfac_find = (cli.isSondeforFactor()||cli.isSbfFactor()) == isFactor;
			}
			
			if(datas.get(Client_DBAO.SEARCH_IS_SFAC) != null)
			{
				boolean isSfac = (boolean)datas.get(Client_DBAO.SEARCH_IS_SFAC);
				factor_find = (cli.isSondeforSfac()||cli.isSbfSfac()) == isSfac;
			}
			
			if(company_find && zipcode_find && city_find && public_find && sfac_find && factor_find)
				values.add(clients.indexOf(cli));
		}
		this.vw_search.setRefine(values);
	}

	
	@Override
	public void search(HashMap<Integer, Object> datas)
	{
		search = new Thread(new Runnable() 
		{
			@Override
			public void run() 
			{
				clients = new Client_DBAO("cli").search(datas);
				((Search_Client_View)vw_search).setResult(clients);
			}
		});
		search.start();
	}
}
