/*
 * To change this template, choose Tools | Templates and open the template in the editor.
 */
package com.onesteel.reinforcing.smartgwtdemo.web.gwt.client;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

import com.allen_sauer.gwt.log.client.Log;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT.UncaughtExceptionHandler;
import com.google.gwt.user.client.Window;
import com.smartgwt.client.data.Record;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.types.Overflow;
import com.smartgwt.client.widgets.IButton;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.FormItemValueFormatter;
import com.smartgwt.client.widgets.form.fields.FormItem;
import com.smartgwt.client.widgets.form.fields.SelectItem;
import com.smartgwt.client.widgets.form.fields.events.ChangedEvent;
import com.smartgwt.client.widgets.form.fields.events.ChangedHandler;
import com.smartgwt.client.widgets.grid.CellFormatter;
import com.smartgwt.client.widgets.grid.EditorValueMapFunction;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.grid.events.EditorExitEvent;
import com.smartgwt.client.widgets.grid.events.EditorExitHandler;
import com.smartgwt.client.widgets.layout.VLayout;

public class CasualHoursEntryPoint implements EntryPoint
{
	
	private LinkedHashMap<String, String> branches;
	private Map<String, LinkedHashMap<String, String>> businessUnits;
	
	public CasualHoursEntryPoint()
	{
		Log.debug("CasualHoursEP constructor(): Creating a new Casual Hours Entry Point");

		branches = new LinkedHashMap<String, String>();

		branches.put("B1", "Branch 1");
		branches.put("B2", "Branch 2");
		
		LinkedHashMap<String, String> b1 = new LinkedHashMap<String, String>();
		b1.put("BU1.1", "Branch 1 - Unit 1");
		b1.put("BU1.2", "Branch 1 - Unit 2");
		
		LinkedHashMap<String, String> b2 = new LinkedHashMap<String, String>();
		b2.put("BU2.1", "Branch 2 - Unit 1");
		b2.put("BU2.2", "Branch 2 - Unit 2");

		businessUnits = new HashMap<String, LinkedHashMap<String, String>>();
		businessUnits.put("B1", b1);
		businessUnits.put("B2", b2);
	}

	/**
	 * To ensure {@link UncaughtExceptionHandler} can catch any unexpected exceptions, all
	 * application initialization code is deferred to {@link #onModuleLoad2()}.
	 *
	 * (non-Javadoc)
	 * 
	 * @see com.google.gwt.core.client.EntryPoint#onModuleLoad()
	 */
	@Override
	public void onModuleLoad()
	{
        //create the order form  
        final DynamicForm buForm = new DynamicForm();  
  
		final SelectItem branchSelectItem = new SelectItem("Branch");
		branchSelectItem.setTitle("Branch");
		branchSelectItem.setValueMap(branches);
        final ListGrid buList = new ListGrid();
        buList.setHeight(200);


		ListGridField buNameListField = new ListGridField("businessunitname", "Name");
		ListGridField buCodeListField = new ListGridField("businessunitcode", "Code");
		
		ListGridField buCodeGrdField = new ListGridField("businessunitcode", "Business Unit");
		buCodeGrdField.setCellFormatter(new CellFormatter()
		{
			
			@Override
			public String format(Object value, ListGridRecord r, int rowNum, int colNum)
			{
				CasualHourRecord chr = (CasualHourRecord) r;
				String formattedValue = chr.getBusinessUnitCode() + " - " + chr.getBusinessUnitName(); 
				return formattedValue; 
			}
		});

		buCodeGrdField.addEditorExitHandler(new EditorExitHandler(){

			@Override
			public void onEditorExit(EditorExitEvent event)
			{
				Log.debug("OnEditorExit: start");
				Log.debug("OnEditorExit: Refreshing row: " + event.getRowNum() + ", col: " + event.getColNum());
				Record s = event.getRecord();
				Log.debug("OnEditorExit: Selected record is " + (s ==null ? "null" : "NOT null"));
				
				CasualHourRecord r = (CasualHourRecord) s;
				String buCode = (String) event.getNewValue();
				Log.debug("OnEditorExit: New Value: " + buCode);
				if( buCode != null) {
//					r.setBusinessUnitName(CasualHoursView.this.model.getBUByBranch().get(buCode));

					buList.refreshCell(event.getRowNum(), event.getColNum());
				}
				Log.debug("OnEditorExit: finished");
			}});


        final SelectItem buSelectItem = new SelectItem();
		buSelectItem.setAllowEmptyValue(Boolean.FALSE);
		buSelectItem.setDefaultToFirstOption(Boolean.TRUE);
		buSelectItem.setAddUnknownValues(false);
		ListGrid pickListProperties = new ListGrid();
		buSelectItem.setDisplayField("businessunitname");
		buSelectItem.setValueField("businessunitcode");
		buSelectItem.setValueFormatter(new FormItemValueFormatter()
		{
			@Override
			public String formatValue(Object value, Record record, DynamicForm form, FormItem formItem) {
				SelectItem selectItem = new SelectItem(formItem.getJsObj());
				ListGridRecord r = selectItem.getSelectedRecord();
				String formattedValue = r.getAttributeAsString("businessunitcode").trim() + " - "+ r.getAttribute("businessunitname").trim(); 
				return formattedValue; 
			}
		});


		buSelectItem.setPickListWidth(300);
		buSelectItem.setPickListProperties(pickListProperties);
		buSelectItem.setPickListFields(buCodeListField, buNameListField);
		buSelectItem.setAddUnknownValues(false);
		buCodeGrdField.setEditorValueMapFunction(new EditorValueMapFunction()
		{
			@SuppressWarnings("rawtypes")
			public Map getEditorValueMap(Map values, ListGridField field, ListGrid grid)
			{
				String branch = (String) branchSelectItem.getValue(); 
				Log.debug("getEditorValueMap: branch is " + branch);
				return businessUnits.get(branch);
			}
		});
		buCodeGrdField.setEditorType(buSelectItem);
		buCodeGrdField.setWidth("20%");
		buCodeGrdField.setCanEdit(Boolean.TRUE);

		buCodeGrdField.setEditorType(buSelectItem);
		buCodeGrdField.setWidth("20%");
		buCodeGrdField.setCanEdit(Boolean.TRUE);

		buList.setFields(buCodeGrdField);
		buList.setCanEdit(Boolean.TRUE);

        buForm.setFields(branchSelectItem);  
        
		final IButton addButton = new IButton("Add");
		addButton.setLayoutAlign(Alignment.CENTER);
		addButton.setOverflow(Overflow.VISIBLE);
		addButton.addClickHandler(new ClickHandler()
		{
			@SuppressWarnings("rawtypes")
			private String getFirst(Set bzUnits)
			{
				for(Object o : bzUnits)
				{
					return (String) o;
				}
				return "";
			}

			public void onClick(ClickEvent event)
			{
				try
				{
					if(branchSelectItem.getValue() == null)
					{
						Window.alert("Please select Branch first.");
						return;
					}

					String branch = (String) branchSelectItem.getValue();
					Log.debug("Add button - onClick: Branch = " + branch);
					String bzUnit = getFirst(businessUnits.get(branch).keySet());
					Log.debug("Add button - onClick: Business unit = " + bzUnit);
					String bzUnitName = businessUnits.get(branch).get(bzUnit);
					Log.debug("Add button - onClick: Business unit name = " + bzUnitName);
					CasualHourRecord newCHRecord =
							new CasualHourRecord(
									bzUnit, bzUnitName, branch, CasualHourRecord.REC_STATE_NEW);
					buList.addData(newCHRecord);
					
				}
				catch(Exception e)
				{
					Window.alert(e.getMessage() + " " + e.toString());
				}
			}
		});

		branchSelectItem.addChangedHandler(new ChangedHandler()
		{
			@Override
			public void onChanged(ChangedEvent event)
			{
				String branch = (String) branchSelectItem.getValue();
				Log.debug("Branch changed: Branch = " + branch);

				buList.selectAllRecords();
				buList.removeSelectedData();
				buSelectItem.clearValue();
				buSelectItem.setValueMap(businessUnits.get(branch));
			}
		});



        VLayout layout = new VLayout(5);  
        layout.setWidth(500);  
        layout.addMember(buForm); 
        layout.addMember(buList);
        layout.addMember(addButton);
        
        layout.draw();
	}

	public class CasualHourRecord extends ListGridRecord
	{

		public static final String REC_STATE_NEW = "NEW";
		public static final String REC_STATE_EXISTING = "EXISTING";
		public static final String REC_STATE_UPDATED = "UPDATED";
		public static final String REC_STATE_DELETED = "DELETED";

		public CasualHourRecord()
		{
			Log.debug("CasualHoursRecord constructor(): Create a new casual hour record");
		}

		public CasualHourRecord(String businessUnitCode,
				String businessUnitName, String branch, String recState)
		{
			Log.debug("CasualHoursRecord constructor(): Create a new casual hour record");
			if(businessUnitCode != null)
				setBusinessUnitCode(businessUnitCode);
			if(businessUnitName != null) {
				setBusinessUnitName(businessUnitName);
			}
			if(branch != null)
				setBranch(branch);
			setRecState(recState);
		}

		public void setBusinessUnitCode(String businessUnitCode)
		{
			Log.debug("setBusinessUnitCode(): Set the business unit code to: " + businessUnitCode);
			setAttribute("businessunitcode", businessUnitCode);
			Log.debug("setBusinessUnitCode(): Business unit code has been set");
		}

		public String getBusinessUnitCode()
		{
			Log.debug("getBusinessUnitCode(): Get the business unit");
			return getAttributeAsString("businessunitcode");
		}

		public void setBusinessUnitName(String businessUnitName)
		{
			Log.debug("setBusinessUnitName(): Set the business unit name to: " + businessUnitName);
			setAttribute("businessunitname", businessUnitName);
			Log.debug("setBusinessUnitName(): Business unit name has been set");
		}

		public String getBusinessUnitName()
		{
			Log.debug("getBusinessUnitName(): Get the business unit name");
			return getAttributeAsString("businessunitname");
		}

		public void setBranch(String Branch)
		{
			Log.debug("setBranch(): Set the branch to: " + Branch);
			setAttribute("Branch", Branch);
			Log.debug("setBranch(): Branch has been set");
		}

		public String getBranch()
		{
			Log.debug("getBranch(): Get the branch");
			return getAttributeAsString("Branch");
		}

		public void setRecState(String recState)
		{
			Log.debug("setRecState(): Set record state to: " + recState);
			setAttribute("recState", recState);
			Log.debug("setRecState(): Record state has been set");
		}

		public String getRecState()
		{
			Log.debug("getRecState(): Get record state");
			return getAttributeAsString("recState");
		}

		public String toString()
		{
			Log.debug("toString(): Convert the Casual hour record to a String");
			return "Businessunit:" + this.getBusinessUnitCode() 
					+ "RecState:" + this.getRecState();
		}

	}

}
