package ibase.client;



import ibase.e12ria.e12table.client.AbstractDataGrid;
import ibase.e12ria.e12table.client.ColumnInfoBean;
import ibase.e12ria.e12table.client.DataGridTableRowModel;
import ibase.e12ria.e12table.client.E12CustomColumn;
import ibase.e12ria.e12table.client.E12CustomTextCell;
import ibase.e12ria.e12table.client.ResizableHeader;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.TreeMap;

import com.google.gwt.cell.client.TextCell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.logical.shared.ResizeEvent;
import com.google.gwt.event.logical.shared.ResizeHandler;
import com.google.gwt.i18n.shared.DateTimeFormat;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.user.cellview.client.ColumnSortEvent;
import com.google.gwt.user.cellview.client.ColumnSortEvent.ListHandler;
import com.google.gwt.user.cellview.client.E12SimplePager;
import com.google.gwt.user.cellview.client.Header;
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.xml.client.Node;
/**
 * This class is used to show the data in paged format.
 * 
 * @author base
 */

public class CustomGrid extends AbstractDataGrid<DataGridTableRowModel>
{
	private String rangeText = "50";
	ListDataProvider<DataGridTableRowModel> dataProvider = new ListDataProvider<DataGridTableRowModel>();	
	ArrayList<DataGridTableRowModel> dataGridTableRowList = new ArrayList<DataGridTableRowModel>();
	PopupPanel contextMenuPanel = new PopupPanel(true);
	public CustomGrid(int pageSize) {
		super(pageSize);
	}

	@Override
	public void refresh() {
		
	}

	@Override
	public void performDoubleClick() {
		
	}

	@Override
	public void createContextMenu() {
		
	}

	@Override
	public void showContextMenu(int selectedRow, int xPosition, int yPosition) {
		
	}
    
	@SuppressWarnings("unchecked")
	public FlexTable jsonToArrayList(HashMap<String, HashMap> gridNGraphMeataDataMap,JSONObject jsonObjGridData ,String dataSrc,String componentId)
	{
		
		DataGridTableRowModel rowDataGrid= null;
		E12CustomTextCell.CellData celldata = null;
		
		ArrayList<ColumnInfoBean> dataGridTableColList = new ArrayList<ColumnInfoBean>();
		FlexTable flexTable= new FlexTable();
		//for arraylist of DataGridTableRowModel object (rows of data)
		HashMap<Integer, E12CustomTextCell.CellData> rowData =  null;
		gridNGraphMeataDataMap.toString().replace('=', ':');
		HashMap<String, ArrayList<String>> graphDataMap = null;
		HashMap<String, ArrayList<String>>  graphSizeMap=null;
		HashMap<String, ArrayList<String>>  graphCaptioneMap=null;
		HashMap<String, ArrayList<String>>  graphAlignMap = null;
		ArrayList<String> graphDtlList = new ArrayList<String>();
		ArrayList<String>  graphAlignList=new ArrayList<String>();	
		ArrayList<String>  graphCaptionList=new ArrayList<String>();	
		
		try
		{
			graphDataMap=gridNGraphMeataDataMap.get(componentId);
			JSONObject jsonEachRow = null;
			JSONObject jsonObjData =(JSONObject) jsonObjGridData.get(dataSrc);
			int count=0;
			for(int jRowCtr=0;jRowCtr<jsonObjData.size();jRowCtr++)
			{
			rowData = new HashMap<Integer, E12CustomTextCell.CellData> ();	
			
			for (String graphKey : graphDataMap.keySet())
			{
				graphDtlList = graphDataMap.get(graphKey);
				jsonEachRow = new JSONObject();
			    jsonEachRow = (JSONObject)jsonObjData.get(""+jRowCtr);
			    count=rowData.size();
				for(int jDataCtr=0;jDataCtr<graphDtlList.size();jDataCtr++)
				{
				 celldata =  new E12CustomTextCell.CellData((""+jsonEachRow.get(""+graphDtlList.get(jDataCtr))).replace('"', ' '));	
				 celldata.setMandatory(true);
				 celldata.setOriginalText("Cell"+jDataCtr);
				 celldata.setName(""+(graphDtlList.get(jDataCtr)).replace('"', ' '));
				 rowData.put(count, celldata);
				 count++;
				}				
			}
			rowDataGrid = new DataGridTableRowModel(rowData);	
			dataGridTableRowList.add(rowDataGrid);
			}
			ColumnInfoBean columnInfoBean=null;
			graphDataMap  =gridNGraphMeataDataMap.get("columnName"+componentId);
			graphSizeMap  =gridNGraphMeataDataMap.get("columnSize"+componentId);
			graphAlignMap =gridNGraphMeataDataMap.get("columnAlign"+componentId);
			graphCaptioneMap = gridNGraphMeataDataMap.get("componentCaption"+componentId);
			for (String graphKey : graphDataMap.keySet())
			{
				graphDtlList.clear();
				graphDtlList = graphDataMap.get(graphKey);
				for(int jDataCtr=0;jDataCtr<graphDtlList.size();jDataCtr++)
				{
					columnInfoBean = new ColumnInfoBean(""+(graphDtlList.get(jDataCtr)),"physicalName", "logicalName", ""+graphSizeMap.get(graphKey));
					dataGridTableColList.add(columnInfoBean);
					graphAlignList.add(""+graphAlignMap.get(graphKey));
				}
			}
			graphCaptionList.add(""+graphCaptioneMap.get("componentCaption"+componentId));
			flexTable.setStyleName("flexCSS");
			flexTable=createTableComponent(dataGridTableRowList,dataGridTableColList,flexTable,graphAlignList,graphCaptionList);
		} catch (Exception e)
		{
			Window.alert(" Exception : DataGrid : jsonToArrayList(): [" + e.getMessage() + "]");
		}
		return flexTable;
	}
	
	
	/**
	 * It creates The AdvDataGrid Table .
	 * 
	 * @param dataGridTableRowList
	 * @return 
	 */
	public FlexTable createTableComponent( ArrayList< DataGridTableRowModel> dataGridTableRowList, ArrayList<ColumnInfoBean> dataGridTableColList, FlexTable flexTable,ArrayList<String> graphAlignList,ArrayList<String> graphCaptionList) 
	{
		final int noOfRows = dataGridTableRowList.size();
		final int noOfColumns = dataGridTableColList.size();

		dataProvider.setList( dataGridTableRowList );
		//Add by Dnyaneshwar chavan on 07-DEC-2012 [WS2GSUN002 ||  ] Start
		E12CustomColumn firstColumn = null;
		//Add by Dnyaneshwar chavan on 07-DEC-2012 [WS2GSUN002 ||  ] End
		String caption ="";
		ResizableHeader<DataGridTableRowModel> header=null;
		try
		{
			E12CustomTextCell.isValidate = false;
			E12CustomTextCell.currentCellElement = null;
			E12CustomTextCell.currentContext = null;
			E12CustomTextCell.incrFactor = 0;
			E12CustomTextCell.editableField = null;
			E12CustomTextCell.prvEditableField = null;
			//  handler for table sorting 
			final ListHandler<DataGridTableRowModel> sortHandler = new ListHandler<DataGridTableRowModel>( dataProvider.getList())
					{
						@Override
						public void onColumnSort(ColumnSortEvent event) {
							super.onColumnSort(event);
							dataProvider.refresh();
						}
					};
			this.addColumnSortHandler(sortHandler);
			int width = 0;
			for( int i= 0  ; i < noOfColumns ; i++ )
			{
				final int index = i;
			    ColumnInfoBean colInfo = dataGridTableColList.get( i );
			    final String colName = colInfo.getDisplayNameOfCol();
			    width = colInfo.getWidth();
				E12CustomColumn column = new E12CustomColumn(i, false);
				column.setSortable( true );
				if(graphAlignList.get(i).trim().equalsIgnoreCase("left"))
				{
					column.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
				}
				else if(graphAlignList.get(i).trim().equalsIgnoreCase("right"))
				{
					column.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);
				}
				else if(graphAlignList.get(i).trim().equalsIgnoreCase("center"))
				{
					column.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
				}
				if ( i == 0 )
				{
					firstColumn = column;
				}
				final String dispDate ="12/12/2014";
				this.setColumnWidth( column, width +"px" );
				header = new ResizableHeader<DataGridTableRowModel>(colName, this, column ) {
					@Override
					public String getValue() {
						return colName;
					}
				};
				Header<String> footer1 = new Header<String>(new TextCell()) {
					
					@Override
					public String getValue() {
						return "";
					}
				};
				
				this.addColumn(column, header, null);
			}
			caption = graphCaptionList.get(0);
			dataProvider.addDataDisplay( this );
			dataProvider.refresh();
			this.getColumnSortList().clear();
			this.getColumnSortList().push( firstColumn );
			this.getColumnSortList().push( firstColumn );
			ColumnSortEvent.fire(this, this.getColumnSortList());
		}
		catch (Exception e )
		{
			Window.alert("Exception in table "+ e.getMessage()) ;
		}
		GridThemes.applyDatagridThemes();
		//E12SimplePager.Resources pagerResources = GWT.create(E12SimplePager.Resources.class);
		//final E12SimplePager pager =new E12SimplePager(E12SimplePager.TextLocation.CENTER, pagerResources, false, 0 , true);
		
		
		HorizontalPanel excelBtnPnl = new HorizontalPanel();
		Button excelBtn = new Button();
		excelBtn.setTitle("Excel");
		Image excelImg = new Image("FusionChart/images/excel.png");
		excelImg.setHeight("20px");
		excelBtn.getElement().appendChild(excelImg.getElement());
		excelBtnPnl.add(ibase.client.tabletoexcel.TableToExcelClientBuilder.fromTable(flexTable).withWidget(excelBtn).buildExportFormWidget());
		SimplePager.Resources displayPagerResources = GWT.create(SimplePager.Resources.class);
		final SimplePager displayPager = new SimplePager(SimplePager.TextLocation.CENTER, displayPagerResources, false, 0 , true, excelBtnPnl);
		displayPager.setDisplay(this);
		displayPager.setRangeText(rangeText);
		Command setRowCmd = new Command() {
			@Override
			public void execute() 
			{
				try
				{
					int rowNo= (int)Double.parseDouble( displayPager.getRangeText().trim() );
					if( rowNo > 0 && rowNo <= noOfRows)
					{
					    CustomGrid.this.setPageSize( rowNo );
					    displayPager.firstPage();
						dataProvider.refresh();
						rangeText = displayPager.getRangeText();
						displayPager.setRangeText(displayPager.getRangeText());
					}
					else
					{
						displayPager.setRangeText("Error");
					}
				}
				catch (Exception e)
				{
					displayPager.setRangeText("Error");
				}
			}
		};
		displayPager.setRangeCommand( setRowCmd );	
		
		if(caption.trim().length()!=0)
		{
			flexTable.setText(0, 0, caption);
			flexTable.setWidget(1, 0, this);
			flexTable.setWidget(2, 0, displayPager);
			flexTable.getCellFormatter().setStyleName(0 ,0 , "FlexTable-ColumnHeaderCell");
			flexTable.getCellFormatter().setStyleName(1 ,0 , "gwt-ScrollTable");
			
			if( GridThemes.getBrowserVersion() == -1 )
			{
				flexTable.getCellFormatter().setStyleName(2 ,0 , "e12Pager");
			}
			else
			{
				flexTable.getCellFormatter().setStyleName(2 ,0 , "e12Pager-forIE");
			}
			
		}else
		{
			flexTable.setWidget(0, 0, this);
			flexTable.setWidget(1, 0, displayPager);
			flexTable.getCellFormatter().setStyleName(0 ,0 , "gwt-ScrollTable");
			
			if( GridThemes.getBrowserVersion() == -1 )
			{
				flexTable.getCellFormatter().setStyleName(1 ,0 , "e12Pager");
			}
			else
			{
				flexTable.getCellFormatter().setStyleName(1 ,0 , "e12Pager-forIE");
			}
			
		}
		flexTable.setHeight( Window.getClientHeight() - 195 + "px" );
		setHeight( Window.getClientHeight() - 207+ "px" );
		setHeight( ( ( Window.getClientHeight() - 207 ))+ "px" );
		
		/*flexTable.setText(0, 0, caption);
	    flexTable.setWidget(1, 0, this);
		flexTable.setWidget(2, 0, displayPager);
		//flexTable.setWidth( Window.getClientWidth() -10+ "px" );
		//flexTable.setWidth("100% !important");
		flexTable.getCellFormatter().setStyleName(0 ,0 , "FlexTable-ColumnHeaderCell");
		flexTable.getCellFormatter().setStyleName(1 ,0 , "gwt-ScrollTable");
		//flexTable.getCellFormatter().setStyleName(1 ,0 , "e12Pager");
		if( GridThemes.getBrowserVersion() == -1 )
		{
			flexTable.getCellFormatter().setStyleName(2 ,0 , "e12Pager");
		}
		else
		{
			flexTable.getCellFormatter().setStyleName(2 ,0 , "e12Pager-forIE");
		}*/
		addStyleName("e12AdvDataGrid-SideBars");
		
		return flexTable;
	}
	
	@Override
	public FlexTable createTableComponent(
			ArrayList<DataGridTableRowModel> dataGridTableRowList,
			TreeMap<Integer, Object> dataGridTableColList) {
		return null;
	}

	@Override
	public FlexTable createTableComponent(ArrayList<DataGridTableRowModel> dataGridTableRowList,
			ArrayList<ColumnInfoBean> dataGridTableColList, FlexTable flexTable) 
	{
		// TODO Auto-generated method stub
		return null;
	}
  
	
	public void showOptionMenu() 
	{
		//DataGridTableRowModel obj = getVisibleItem(selectedRow);
		//getSelectionModel().setSelected(obj, true);
		//this.selDataGridTRModel = obj;
//		createContextMenu();
		//performOnTouch();	
		{
			final E12CustomAnimation slideAnim = new E12CustomAnimation(contextMenuPanel.getElement());
			final int left_to = Window.getClientWidth() - 170;
			final int left_from = Window.getClientWidth();
		
				slideAnim.scrollFromAndTo(left_from, 40, left_to, 40, 500);
				Window.addResizeHandler(new ResizeHandler() {
					@Override
					public void onResize(ResizeEvent event) {
						int left_to1 = Window.getClientWidth() - 170;
						int left_from1 = Window.getClientWidth();
						slideAnim.scrollFromAndTo(left_from1, 40, left_to1, 40, 500);
					}
				});
			
			
				contextMenuPanel.setHeight(Window.getClientHeight() - 80 + "px");
		}
			contextMenuPanel.setStyleName("slidePopupPanel");
			contextMenuPanel.setAutoHideEnabled(true);
			contextMenuPanel.show();
		}		
	
	
	

}
