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.DataSource;
import com.smartgwt.client.data.RestDataSource;
import com.smartgwt.client.data.fields.DataSourceTextField;

public class BankTreeDataSource extends RestDataSource {

	public static final String VALUE = "value";
	
	private static Map<String, BankTreeDataSource> dataSources = new HashMap<String, BankTreeDataSource>();
	
	private BankTreeDataSource(String bankName) {
		setID("treeDataSource_" + bankName);
		
		DataSourceTextField pkField = new DataSourceTextField("id");
		pkField.setHidden(true);
		pkField.setPrimaryKey(true);
		pkField.setRequired(true);
		
		DataSourceTextField fkField = new DataSourceTextField("parent");
		fkField.setHidden(true);
		fkField.setForeignKey(".id");
		fkField.setRootValue("1");
		fkField.setRequired(true);
		
		DataSourceTextField value = new DataSourceTextField(VALUE);
		
		
		setFields(pkField, fkField, value);
		
		// Url of the servlet to contact
		setDataURL(GWT.getModuleName() + "/bankDetailService?getxml=" + bankName);
		
	}
	
	private void updateDataURL(String key) {
		Map<String, String> auth = new HashMap<String, String>();
		
		// Authenticate
		if (key != null) {
			auth.put("auth_key", key);	
		}
		
		setDefaultParams(auth);
	}
	
	public static DataSource getInstance(String bankName, String key) {
		
		BankTreeDataSource ds; 
		if ((ds = dataSources.get(bankName)) == null) {
			ds = new BankTreeDataSource(bankName);
			dataSources.put(bankName, ds);
		}
		
		ds.updateDataURL(key);
		
		return ds;
	}

}
