package org.inria.bmajwatcher.client.ui;


import java.util.HashMap;
import java.util.Map;

import com.google.gwt.core.client.GWT;
import com.smartgwt.client.data.RestDataSource;
import com.smartgwt.client.data.fields.DataSourceImageField;
import com.smartgwt.client.data.fields.DataSourceIntegerField;
import com.smartgwt.client.data.fields.DataSourceTextField;

/**
 * Datasource that is binded to the bank list component and that queries
 * the appropriate service on the server to retrieve the required data.
 * 
 * @author rsabas
 *
 */
public class BankGridDataSource extends RestDataSource {

	public static final String TYPE 	= "type";
	public static final String FORMATS 	= "formats";
	public static final String NAME		= "name";
	public static final String RELEASE 	= "release";
	public static final String STATUS	= "status";
	public static final String SESSION	= "session";
	public static final String IS_SCHED = "isSched";
	public static final String VISIBILITY = "visibility";
	public static final String OWNER	= "owner";
	public static final String GROUP	= "group";
	
	private static BankGridDataSource instance = new BankGridDataSource();
	
	private BankGridDataSource() {
		
		setID("gridDataSource");
		
		DataSourceIntegerField pkField = new DataSourceIntegerField("id");
		pkField.setHidden(true);
		pkField.setPrimaryKey(true);
		
		DataSourceImageField schedField = new DataSourceImageField(IS_SCHED);
		DataSourceTextField name = new DataSourceTextField(NAME);
		DataSourceTextField type = new DataSourceTextField(TYPE);
		DataSourceTextField formats = new DataSourceTextField(FORMATS);
		DataSourceTextField release = new DataSourceTextField(RELEASE);
		DataSourceTextField status = new DataSourceTextField(STATUS);
		DataSourceTextField session = new DataSourceTextField(SESSION);
		DataSourceTextField owner = new DataSourceTextField(OWNER);
		DataSourceTextField group = new DataSourceTextField(GROUP);
		DataSourceImageField visibility = new DataSourceImageField(VISIBILITY);
		
		setFields(schedField, type, formats, name, release, session, status, visibility, owner, group);
		// Url of the servlet to contact
		setDataURL(GWT.getModuleName() + "/bankListingService");
	}
	
	private static void updateDataURL(String key) {
		Map<String, String> auth = new HashMap<String, String>();
		
		// Authenticate
		if (key != null) {
			auth.put("auth_key", key);	
		}
		
		instance.setDefaultParams(auth);
	}
	
	public static BankGridDataSource getInstance(String key) {
		updateDataURL(key);
		return instance;
	}

}
