package com.ssdi.test.client;

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



import com.smartgwt.client.widgets.menu.Menu;
import com.smartgwt.client.widgets.menu.MenuItem;
import com.smartgwt.client.data.Criteria;
import com.smartgwt.client.types.AutoFitWidthApproach;
import com.smartgwt.client.types.FetchMode;
import com.smartgwt.client.types.ListGridComponent;
import com.smartgwt.client.types.SelectionAppearance;
import com.smartgwt.client.types.SelectionStyle;
import com.smartgwt.client.util.Offline;
import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.events.DrawEvent;
import com.smartgwt.client.widgets.events.DrawHandler;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.events.FieldStateChangedEvent;
import com.smartgwt.client.widgets.grid.events.FieldStateChangedHandler;
import com.smartgwt.client.widgets.menu.MenuItemIfFunction;
import com.smartgwt.client.widgets.menu.MenuItemSeparator;
import com.smartgwt.client.widgets.menu.events.MenuItemClickEvent;
import com.smartgwt.client.widgets.toolbar.ToolStrip;
import com.smartgwt.client.widgets.toolbar.ToolStripButton;
/**
 * @author raghavendraraju
 * 
 */
public abstract class SecDBListGrid extends ListGrid {

	private MenuItem simpleFilterMenuItem;
	private MenuItem resetFilterMenuItem;
	protected String groupId = null;
	private boolean filterFlag = false;

	
	// list grid methods
	
	/**
     * set custom messages on list grid   
     */
	public abstract void setMessages();
	
	/**
     * get custom criteria required to apply list grid    
     */
	public abstract Criteria getCriteria();

	/**
	 * add list grid fields         
     */
	public abstract void addListGridField();

	/**
	 * unique id per list grid and used for storing and retrieving list grid column state         
     */
	public abstract String getListGridId();
	
	/**
	 *  true to display the list grid with check box        
     */
	public abstract boolean isSelectionType();
	
	//private SecDBToolStrip secDBToolStrip;
	
	/**
	 * Class constructor. used for default implementation
	 */
	/*public FSSListGrid() {
		setListGridProperties();
		// Permission Settings For Login user
		if (PermissionSettings.getPermissionSettings()
				.getDeviceManagementAuthority().isView()) {
			setSelectionAppearance(SelectionAppearance.CHECKBOX);
		}
	}*/
	public SecDBListGrid(){
		setListGridProperties();
	}
	

	
	public SecDBListGrid(String groupId) {		
		this.groupId = groupId;
		setListGridProperties();
	}
	/**
	 * set basic properties
	 */	    
	private void setListGridProperties() {
		setID(getListGridId()+ groupId);
		setWidth100();
		setHeight100();
		setMargin(10);
		setLeaveScrollbarGap(false);
		setShowRollOver(false);
		setShowFilterEditor(false);
		setCanAutoFitFields(true);
		setCanResizeFields(true);
		
		if(isSelectionType()){
			setSelectionType(SelectionStyle.SIMPLE);	
			setSelectionAppearance(SelectionAppearance.CHECKBOX);
		}
		setAutoFitWidthApproach(AutoFitWidthApproach.BOTH);
		setMessages();
		setShowEmptyMessage(true);
	/*	setEmptyMessage( resourceString.getLocalizedString(localizedStringKey
			    .getSecDBNoDevicesToShow()));*/
		setShowFilterEditor(false);
		setFilterOnKeypress(true);
		setFetchDelay(500);
		setWarnOnRemoval(true);
		setShowRecordComponents(true);
		//setShowRecordComponentsByCell(true);
		Criteria criteria = getCriteria();
		if (criteria != null) {
			setInitialCriteria(getCriteria());
		}
		addListGridField();
		addProperties();
		addDS();
		initToolStrip();
		applyFieldState();
	}
	
	public boolean isToolStripRequired(){
	    return true;
	}
	
	/**
	 * store list grid column fields in off line     
     */
	public void storeFieldState(){
		Offline.put(getListGridId(), getViewState());
	}
	
	/**
	 * Simple Filter As a Context Menu Item     
     */
	public boolean addSimpleFilterMenuItem(){
		return false;
	}
	
	/**
	 * Simple Filter As a Context Menu Item     
     */
	public boolean getSimpleFilterMenuItemsFlag(){
		filterFlag = addSimpleFilterMenuItem();
		return filterFlag;
	}

	
	/**
	 * add data source if data source is not null
	 */
	public void addDS(){
		if(getDS()!=null){
			setDS();
		}
		
	}

	/**
	 * apply list grid column state
	 */
	public void applyFieldState(){
		try{
							
			final String viewState = (String) Offline
			.get(getId());
			if(viewState!=null){
				addDrawHandler(new DrawHandler() {  
		            @Override  
		            public void onDraw(DrawEvent event) {  
		                //restore any previously saved view state for this grid  
		            	setViewState(viewState);  
		            }  
		        }); 
			}
		}catch(Exception e){
			e.printStackTrace();
		} 
		FieldStateChangedHandler fieldStateChangedHandler = new FieldStateChangedHandler() {

			@Override
			public void onFieldStateChanged(FieldStateChangedEvent event) {
				Offline.put(getId(), getViewState());
				updateFieldChangeCallBack();
			}
		};
		addFieldStateChangedHandler(fieldStateChangedHandler);
	}
	
	private String getId(){
		return null;
	}
	
	public void updateFieldChangeCallBack(){
		
	}
	
	// tool strip methods	
	public abstract String getTotalCountLabel();
	
	public abstract String getSelectedCountLabel();
	
	public  String getFilteredCountLabel(){
		return null;
	}
	
	
	public abstract ToolStripButton getToolStripButton();	
	
	/**
	 * get tool strip	
	 */
	public ToolStrip getTooStrip(){
		return null;
	}
	
	/**
	 * initialize the tool strip
	 */
	public void initToolStrip(){
		
		
		
		addGridComponents();
		
	}
	
	/**
	 * add grid components	
	 */
	public void addGridComponents(){
	//	setDefaultGridComponents(getSecDBToolStrip().getToolStrip());		
	}
	
	/**
	 * add list grid properties
	 */	
	public void addProperties(){
		setCellHeight(30);
		setHeaderHeight(30);
	}
	
		
	/**
	 * refresh list grid
	 */
	public void refresh() {
		invalidateCache();
		scrollToRow(0);
	}

	/**
	 * set data source with pagination
	 */
	public void setDS() {		
		setDataSource(getDS());
		setAutoFetchData(true);
		setDataFetchMode(FetchMode.PAGED);
		setDataPageSize(30);
		// Added Paging support
	}
	
	/**
	 * get list grid data source
	 */
	public abstract AbstractBaseDS getDS();

	/**
	 *  returns the menu items to be displayed in the default header context menu.
	 *  
     * @param fieldNum index of the field the user clicked in the fields array.
     * @return Array of MenuItem
     */
	
	// As per latest specification(R.2.1.1.4) Simple Filter is not there in SecDB
	@Override
	public MenuItem[] getHeaderContextMenuItems(Integer fieldNum) {

		// Step1: Retain the existing menu item in ListGrid Bar
		//
		MenuItem[] superItems = super.getHeaderContextMenuItems(fieldNum);
		List<MenuItem> devicelistgridmenuList = new ArrayList<MenuItem>();
		for (MenuItem item : superItems) {
			devicelistgridmenuList.add(item);
		}
		
		// Step2: Add Custom Menu item Simple filter
		//
		if(getSimpleFilterMenuItemsFlag()){
			
		devicelistgridmenuList.add(new MenuItemSeparator());
	//	simpleFilterMenuItem = new MenuItem(resourceString.getLocalizedString(localizedStringKey.getSecDBSimpleFilter()));
		simpleFilterMenuItem.setIcon("");
		simpleFilterMenuItem.setChecked(false);

		// Step 2.1:
		// for Enabling and disabling Menu item check box
		//
		simpleFilterMenuItem
				.addClickHandler(new com.smartgwt.client.widgets.menu.events.ClickHandler() {

					@Override
					public void onClick(MenuItemClickEvent event) {
						// if enabled then disable the Simple filter grid
						// if disabled then enable the Simple filter grid
						if (getShowFilterEditor()) {
							// enable simple filter bar
							setShowFilterEditor(false);
							//clearCriteria();							
							setAttribute("initialCriteria", getCriteria(), true);
							fetchData(getCriteria());
						} else {
							// disable simple filter bar
							setShowFilterEditor(true);
						}

					}
				});

		// Step 2.2:
		// whether check or un check
		//
		simpleFilterMenuItem.setCheckIfCondition(new MenuItemIfFunction() {

			@Override
			public boolean execute(Canvas target, Menu menu, MenuItem item) {
				return getShowFilterEditor();
			}
		});
		devicelistgridmenuList.add(simpleFilterMenuItem);

		// Step 3.1 Reset Filter Item
		// clear all simple filter conditions
		//
	//	resetFilterMenuItem = new MenuItem(resourceString.getLocalizedString(localizedStringKey.getSecDBResetFilter()));
		resetFilterMenuItem
				.addClickHandler(new com.smartgwt.client.widgets.menu.events.ClickHandler() {
					@Override
					public void onClick(MenuItemClickEvent event) {						
						//clearCriteria();
						setAttribute("initialCriteria", getCriteria(), true);
						fetchData(getCriteria());
					}
				});

		// Step 3.1 Reset Filter Item
		//
		resetFilterMenuItem.setEnableIfCondition(new MenuItemIfFunction() {
			@Override
			public boolean execute(Canvas target, Menu menu, MenuItem item) {
				// Only if Simple filter is enabled then
				// reset filter should be enabled
				//
				return simpleFilterMenuItem.getChecked();
			}
		});
		devicelistgridmenuList.add(resetFilterMenuItem);
		}

		// Return the values
		MenuItem[] newItems = new MenuItem[devicelistgridmenuList.size()];
		devicelistgridmenuList.toArray(newItems);

		return newItems;
	}

	/**
	 * set custom grid component
	 * @param toolStrip is tool strip object
	 * @param listGridComponent is ListGridComponent array object
	 */	
	public void setGridComponents(ToolStrip toolStrip, ListGridComponent... listGridComponent){
		setGridComponents(new Object[] {
				listGridComponent, toolStrip}); 		
	}
	
	/**
	 * set default grid component
	 * @param toolStrip is tool strip object
	 */	
	public void setDefaultGridComponents(ToolStrip toolStrip){
		setGridComponents(new Object[] {
				ListGridComponent.HEADER,ListGridComponent.FILTER_EDITOR, ListGridComponent.BODY, toolStrip}); 		
	}

	

}
