package esos.client.smartWidget.data.benchmark;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.smartgwt.client.data.DSRequest;
import com.smartgwt.client.data.DSResponse;
import com.smartgwt.client.data.DataSourceField;
import com.smartgwt.client.data.fields.DataSourceBooleanField;
import com.smartgwt.client.data.fields.DataSourceDateField;
import com.smartgwt.client.data.fields.DataSourceIntegerField;
import com.smartgwt.client.data.fields.DataSourceTextField;
import com.smartgwt.client.rpc.RPCResponse;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import esos.client.controller.ClientController;
import esos.client.controller.RemoteInterfaceController;
import esos.client.data.ibatisPOJO.BenchmarkRequest;
import esos.client.data.ibatisPOJO.Paging;
import esos.client.lib.DateUtils;
import esos.client.lib.paging.PagingList;
import esos.client.remoteservice.GwtRpcDataSource;
import esos.client.widget.ErrorDialog;

public class BenchmarkRequestDS extends GwtRpcDataSource {
	
	 private static BenchmarkRequestDS instance = null;
	 private BenchmarkRequest filter;
	 public Paging paging = new Paging();

	

	public static BenchmarkRequestDS getInstance(BenchmarkRequest filter) {
	        if (instance == null) {
	            instance = new BenchmarkRequestDS();
	        }
	        instance.setFilter(filter);
	        return instance;
	 }
	 
	public BenchmarkRequestDS(){
		DataSourceField field;
		
		field = new DataSourceIntegerField("requestId","REQUEST_ID");
		field.setPrimaryKey (true);
		field.setHidden(true);
		field.setCanEdit(false);
        addField (field);
        
    	field = new DataSourceTextField("bmId", 
    			ClientController.getLanguage().getBenchmarksReportWidgetBMIDLabel(),10,true);
    	addField (field);
    	
		field = new DataSourceTextField("title", 
		 		ClientController.getLanguage().getEditBenchmarksTitleLabel());
		field.setCanEdit(false);
		addField (field);
		 
	 	field = new DataSourceDateField("actMonth",
				ClientController.getLanguage().getBmRequestActMonth(),10,true);
	  	addField (field);
     	
     	field = new DataSourceTextField("period",
     			ClientController.getLanguage().getBmRequestPeriod(),10,true);
     	Map<String, String> periodTypes = new LinkedHashMap<String, String>();
 		periodTypes.put("MTD",ClientController.getLanguage().getMTD());
 		periodTypes.put("TMRA",ClientController.getLanguage().getTMRA());
 		periodTypes.put("YTD",ClientController.getLanguage().getYTD());
 		periodTypes.put("YRA",ClientController.getLanguage().getYRA());
 		field.setValueMap(periodTypes);
     	addField (field);
     	
     	field = new DataSourceBooleanField("inProgress", 
    			ClientController.getLanguage().getBmRequestInProgress());
    	field.setCanEdit(false);
    	addField (field);
    	
    	field = new DataSourceIntegerField("progress", 
    			ClientController.getLanguage().getBmRequestProgress());
    	field.setCanEdit(false);
    	field.setCanFilter(false);
    	addField (field); 
    	
    	field = new DataSourceTextField("requested", 
    			ClientController.getLanguage().getBmRequestRequested());
    	field.setCanEdit(false);
    	field.setCanFilter(false);
    	addField (field);
    	
    	field = new DataSourceTextField("failureReason", 
    			ClientController.getLanguage().getBmRequestFailureReason());
    	field.setCanEdit(false);
    	field.setCanFilter(false);
    	addField (field);
    	
    	field = new DataSourceBooleanField("completed", 
    			ClientController.getLanguage().getBmRequestCompleted());
    	//field.setCanEdit(false);
    	addField (field);
    	
    	field = new DataSourceDateField("completedDate", 
    			ClientController.getLanguage().getBmRequestCompletedDate());
    	field.setCanEdit(false);
    	field.setCanFilter(false);
    	addField (field);
    	
    	field = new DataSourceBooleanField("posted", 
    			ClientController.getLanguage().getBmRequestPosted());
    	field.setCanEdit(false);
    	addField (field);
    	
    	field = new DataSourceDateField("postedDate", 
    			ClientController.getLanguage().getBmRequestPostedDate());
    	field.setCanEdit(false);
    	field.setCanFilter(false);
    	addField (field);
    	
    /*	field = new DataSourceBooleanField("error", 
    			ClientController.getLanguage().getBmRequestError());
    	field.setCanEdit(false);
    	addField (field);*/
    	
    	
    	
    	
    	
    	field = new DataSourceIntegerField("sampleSize", 
    			ClientController.getLanguage().getBmRequestSampleSize());
    	field.setCanEdit(false);
    	field.setCanFilter(false);
    	addField (field);
    	
    	
    	
    	
        field = new DataSourceTextField("disId", 
        		ClientController.getLanguage().getMapperDmsDistributorWidgetName());
       // field.setCanEdit(false);
        addField (field);
        
       /* field = new DataSourceTextField("distributor", 
        		ClientController.getLanguage().getMapperDmsDistributorWidgetName());
        field.setCanEdit(false);
        addField (field);*/

       
      
        
        
	}
	

	@Override
	protected void executeFetch(final String requestId, final DSRequest request, final DSResponse response) {
		paging.setRequest(request);
		
		filter.setBmId(request.getCriteria().getAttributeAsString("bmId"));
		filter.setTitle(request.getCriteria().getAttributeAsString("title"));
		filter.setDisId(request.getCriteria().getAttributeAsString("disId"));
		if (request.getCriteria().getAttribute("posted")!=null){
			filter.setPosted(request.getCriteria().getAttributeAsBoolean("posted"));
		}else{
			filter.setPosted(null);
		}
		if (request.getCriteria().getAttribute("completed")!=null){
			filter.setCompleted(request.getCriteria().getAttributeAsBoolean("completed"));
		}else{
			filter.setCompleted(null);
		}
		filter.setPeriod(request.getCriteria().getAttributeAsString("period"));
		filter.setActMonth(DateUtils.DateToInt(request.getCriteria().getAttributeAsDate("actMonth")));
		
		RemoteInterfaceController.getBenchmarkService().getBenchmarkRequests(filter,paging, new AsyncCallback<PagingList<BenchmarkRequest>>() {
			public void onFailure (Throwable caught) {
				ErrorDialog.showErrorDialog( caught);
		        response.setStatus (RPCResponse.STATUS_FAILURE);
		        processResponse (requestId, response);
		    }
			public void onSuccess(PagingList<BenchmarkRequest> result) {
				paging.setOnePage(result.getTotalRows()<=result.size());
				if (result.getTotalRows()>result.size()){
		    		response.setTotalRows (result.getTotalRows());
		    	}
		        ListGridRecord[] list = new ListGridRecord[result.size()];
		        for (int i = 0; i < list.length; i++) {
		            ListGridRecord record = new ListGridRecord ();
		            copyValues (result.get(i), record);
		            list[i] = record;
		        }
		        response.setData (list);
		        processResponse (requestId, response);
				
			}
		});
	}

	@Override
	protected void executeUpdate(final String requestId, final DSRequest request, final	DSResponse response) {
		 // Retrieve record which should be updated.
		BenchmarkRequest benchmarkRequest = new BenchmarkRequest ();
        copyValues (new ListGridRecord (request.getData ()), benchmarkRequest);
        
        RemoteInterfaceController.getBenchmarkService().updateBenchmarkRequest(benchmarkRequest,new AsyncCallback<BenchmarkRequest>() {
            public void onFailure (Throwable caught) {
            	ErrorDialog.showErrorDialog(  caught);
                //response.setStatus (RPCResponse.STATUS_FAILURE);
            	response.setStatus(RPCResponse.STATUS_VALIDATION_ERROR);
            	Map<String,String> errors = new HashMap<String,String>();
            	errors.put("requestId", "Validation error");
                processResponse (requestId, response);
            }
            public void onSuccess (BenchmarkRequest result) {
                ListGridRecord[] list = new ListGridRecord[1];
                ListGridRecord newRec = new ListGridRecord ();
                copyValues (result, newRec);
                list[0] = newRec;
                response.setData (list);
                processResponse (requestId, response);
            }
        });
	}
	
	
	@Override
	protected void executeAdd(final String requestId, final DSRequest request, final DSResponse response) {
		// Retrieve record which should be added.
		BenchmarkRequest benchmarkRequest = new BenchmarkRequest ();
        copyValues (new ListGridRecord (request.getData ()), benchmarkRequest);

        RemoteInterfaceController.getBenchmarkService().addBenchmarkRequest(benchmarkRequest,new AsyncCallback<BenchmarkRequest>() {
            public void onFailure (Throwable caught) {
            	ErrorDialog.showErrorDialog(  caught);
                //response.setStatus (RPCResponse.STATUS_FAILURE);
            	response.setStatus(RPCResponse.STATUS_VALIDATION_ERROR);
            	Map<String,String> errors = new HashMap<String,String>();
            	errors.put("bmId", "Validation error");
                processResponse (requestId, response);
            }
            public void onSuccess (BenchmarkRequest result) {
                ListGridRecord[] list = new ListGridRecord[1];
                ListGridRecord newRec = new ListGridRecord ();
                copyValues (result, newRec);
                list[0] = newRec;
                response.setData (list);
                processResponse (requestId, response);
            }
        });
	}
	
	@Override
	protected void executeRemove(final String requestId, final DSRequest request, final DSResponse response) {
		// Retrieve record which should be deleted.
        final ListGridRecord rec = new ListGridRecord (request.getData ());
        BenchmarkRequest benchmarkRequest = new BenchmarkRequest ();
        copyValues (new ListGridRecord (request.getData ()), benchmarkRequest);
        
        RemoteInterfaceController.getBenchmarkService().removeBenchmarkRequest(benchmarkRequest,new AsyncCallback<String>() {
            public void onFailure (Throwable caught) {
            	ErrorDialog.showErrorDialog(  caught);
                response.setStatus (RPCResponse.STATUS_FAILURE);
                processResponse (requestId, response);
            }
            public void onSuccess (String result) {
                ListGridRecord[] list = new ListGridRecord[1];
                // We do not receive removed record from server.
                // Return record from request.
                list[0] = rec;
                response.setData (list);
                processResponse (requestId, response);
            }
        });
	}
	
	private void copyValues(BenchmarkRequest from, ListGridRecord to) {
		
		
		to.setAttribute("requestId", from.getRequestId());
		to.setAttribute("requested", from.getRequested());
		to.setAttribute("completed", from.getCompleted());
		to.setAttribute("completedDate", from.getCompletedDate());
		to.setAttribute("posted", from.getPosted());
		to.setAttribute("postedDate", from.getPostedDate());
		//to.setAttribute("error", from.
		to.setAttribute("failureReason", from.getFailureReason());
		to.setAttribute("inProgress", from.getInProgress());
		to.setAttribute("progress", from.getProgress());
		to.setAttribute("sampleSize", from.getSampleSize());
		to.setAttribute("actMonth", DateUtils.parseIntDate(from.getActMonth()));
		/*DateTimeFormat dateFormatter = DateTimeFormat.getFormat("MMM, yyyy");
		String actMonth = dateFormatter.format(DateUtils.parseIntDate(from.getActMonth()));
		to.setAttribute("actMonth", actMonth);*/
		to.setAttribute("period", from.getPeriod());

		to.setAttribute("bmId", from.getBmId());
		to.setAttribute("title", from.getTitle());
		to.setAttribute("useZeroValues", from.getUseZeroValues());
		to.setAttribute("minimalSampleSize", from.getMinimalSampleSize());
		to.setAttribute("autoRunIncrementalSize", from.getAutoRunIncrementalSize());
		to.setAttribute("runIncrementalSize", from.getRunIncrementalSize());
		to.setAttribute("runMinimalSampleSize", from.getRunMinimalSampleSize());
		to.setAttribute("percentile", from.getPercentile());
		to.setAttribute("useDepartmentalMatching", from.getUseDepartmentalMatching());
		to.setAttribute("disId", from.getDisId());
		to.setAttribute("distributor", from.getDistributor().getName());
		to.setAttribute("reportId", from.getReportId());

	}
	
	private void copyValues(ListGridRecord from, BenchmarkRequest to) {
		to.setRequestId(from.getAttributeAsInt("requestId"));
		//to.setRequested(from.getAttributeAsDate("requested"));
		to.setCompleted(from.getAttributeAsBoolean("completed"));
		to.setCompletedDate(from.getAttributeAsDate("completedDate"));
		to.setPosted(from.getAttributeAsBoolean("posted"));
		to.setPostedDate(from.getAttributeAsDate("postedDate"));
		//to.set             ("error", from.
		to.setFailureReason(from.getAttribute("failureReason"));
		to.setInProgress(from.getAttributeAsBoolean("inProgress"));
		to.setProgress(from.getAttributeAsInt("progress"));
		to.setSampleSize(from.getAttributeAsInt("sampleSize"));
		
		/*DateTimeFormat dateFormatter = DateTimeFormat.getFormat("MMM, yyyy");
		Date actMonth = dateFormatter.parse(from.getAttribute("actMonth")); */
		to.setActMonth(DateUtils.DateToInt(from.getAttributeAsDate("actMonth")));
		to.setPeriod(from.getAttribute("period"));
		
		to.setBmId(from.getAttribute("bmId"));
		to.setTitle(from.getAttribute("title"));
		to.setUseZeroValues(from.getAttribute("useZeroValues")==null ? null : from.getAttribute("useZeroValues").equalsIgnoreCase("true"));
		to.setMinimalSampleSize(from.getAttribute("minimalSampleSize")== null ? null : Integer.parseInt(from.getAttribute("minimalSampleSize")));
		to.setAutoRunIncrementalSize(from.getAttribute("autoRunIncrementalSize")== null ? null : Integer.parseInt(from.getAttribute("autoRunIncrementalSize")));
		to.setRunIncrementalSize(from.getAttribute("runIncrementalSize")==null ? null : from.getAttribute("runIncrementalSize").equalsIgnoreCase("true"));
		to.setRunMinimalSampleSize(from.getAttribute("runMinimalSampleSize")==null ? null : from.getAttribute("runMinimalSampleSize").equalsIgnoreCase("true"));
		to.setPercentile(from.getAttribute("percentile")== null ? null : Integer.parseInt(from.getAttribute("percentile")));
		to.setUseDepartmentalMatching(from.getAttribute("useDepartmentalMatching")==null ? null : from.getAttribute("useDepartmentalMatching").equalsIgnoreCase("true"));
		to.setDisId(from.getAttribute("disId"));
		to.getDistributor().setName(from.getAttribute("distributor"));
		to.setReportId(from.getAttribute("reportId")== null ? null : Integer.parseInt(from.getAttribute("reportId")));

		
		from.getAttributes();

	}

	public BenchmarkRequest getFilter() {
		return filter;
	}

	public void setFilter(BenchmarkRequest filter) {
		this.filter = filter;
	}

}
