package be.uniway.rvk.test.datasource.server;

import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import be.uniway.rvk.test.datasource.server.repository.ClientDao;
import be.uniway.rvk.test.datasource.server.repository.impl.ClientDaoImpl;
import be.uniway.rvk.test.datasource.shared.ClientDto;

import com.isomorphic.datasource.BasicDataSource;
import com.isomorphic.datasource.DSRequest;
import com.isomorphic.datasource.DSResponse;


public class DMIHandler extends BasicDataSource {

	private ClientDao clientDao = new ClientDaoImpl();

	public DMIHandler() {
		super();
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public DSResponse executeFetch(DSRequest req) throws Exception {
		List<ClientDto> results = null ;
		Map<String,Object> c = req.getCriteria();
		String userName = null;
		if ( c.containsKey("username") ) {
			userName = c.get("username").toString();
		}
		if ( userName != null ) {
			ClientDto criteria = new ClientDto(null,userName,null);
			results = clientDao.getClientsByCriteria(criteria);
		}
		DSResponse response = null ;
		if ( results != null ) {
			response = new DSResponse();
			response.setStartRow(0L);
			response.setEndRow((results.size())-1);
			response.setTotalRows(results.size());
			response.setData(results);
		}
		return response;
	}

	@Override
	public DSResponse execute(DSRequest req) throws Exception {
		if ( "fetch".equalsIgnoreCase(req.getOperation()) || "clients_fetch".equalsIgnoreCase(req.getOperation()) ) {
			return this.executeFetch(req);
		} else {
			return null;
		}
	}
}
 