package com.islandpacific.gui.client;

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

import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.user.client.ui.TextBox;
import com.smartgwt.client.data.Criteria;
import com.smartgwt.client.data.DSCallback;
import com.smartgwt.client.data.DSRequest;
import com.smartgwt.client.data.DSResponse;
import com.smartgwt.client.data.DataSource;
import com.smartgwt.client.data.Record;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.types.VerticalAlignment;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.IButton;
import com.smartgwt.client.widgets.Label;
import com.smartgwt.client.widgets.Window;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.events.HiddenValidationErrorsEvent;
import com.smartgwt.client.widgets.form.events.HiddenValidationErrorsHandler;
import com.smartgwt.client.widgets.form.fields.CheckboxItem;
import com.smartgwt.client.widgets.form.fields.ComboBoxItem;
import com.smartgwt.client.widgets.form.fields.FormItem;
import com.smartgwt.client.widgets.form.fields.SelectItem;
import com.smartgwt.client.widgets.form.fields.TextItem;
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.layout.HLayout;
import com.smartgwt.client.widgets.layout.LayoutSpacer;
import com.smartgwt.client.widgets.layout.VLayout;

public class PoApprovalDialog extends Window {

	private static final String PO_APPROVAL_FIELD_poList = "PoList";
	private static final String PO_APPROVAL_FIELD_fileGroupNumber = "FileGroupNumber";
	private static final String PO_APPROVAL_FIELD_printPo = "PrintPo";
	private static final String PO_APPROVAL_FIELD_printPackAndShipReports = "PrintPackAndShipReports";
	private static final String PO_APPROVAL_FIELD_printStoreRecievingWorksheet = "PrintStoreRecievingWorksheet";
	private static final String PO_APPROVAL_FIELD_printTicketOrderReport = "PrintTicketOrderReport";
	private static final String PO_APPROVAL_FIELD_printTotalsByColor = "PrintTotalsByColor";
	private static final String PO_APPROVAL_FIELD_printTotalsBySize = "PrintTotalsBySize";
	private static final String PO_APPROVAL_FIELD_printPrepackComponentInformation = "PrintPrepackComponentInformation";
	private static final String PO_APPROVAL_FIELD_poStatusList = "PoStatusList";
	
	private DynamicForm myForm = null;
	private DataSource myPoApprovalDataSource = null;
	
	private Label myApprovePoLabel = null;
	private CheckboxItem myPrintPoCheckbox = null;
	private SelectItem myPrintPackAndShipSelector = null;
	private SelectItem myPrintStoreReceivingWorksheetSelector = null;
	private TextItem myPoApprovalList = null;
	private CheckboxItem myPrintTicketOrderReportCheckbox = null;
	private CheckboxItem myPrintTotalsByColorCheckbox = null;
	private CheckboxItem myPrintTotalsBySizeCheckbox = null;
	private CheckboxItem myPrintPrepackComponentInformationCheckbox = null;
	private HLayout myButtonLayout = null;
	private IpOkCancelCallback myOkCancelCallback = null;
	private String[] myPoNumbers = null;
	private int myFileGroupNumber = 0;
	private String myTitle = null;
	
	/**
	 * This constructor is made private so it cannot be used.
	 */
	private PoApprovalDialog() {
		super();
	}

	/**
	 * Create an object with a callback.
	 * @param okCancelCallback
	 */
	public PoApprovalDialog(IpOkCancelCallback okCancelCallback) {
		super();
		setKeepInParentRect(true);
		setAutoCenter(true);
		// setCanDragResize(true);
		setCanSelectText(true);
		setShowCloseButton(true);
		setShowMinimizeButton(false);
		setShowMaximizeButton(true);
		setShowHeaderIcon(true);
		setShowModalMask(true);
		setIsModal(true); 
		setHeaderIcon("customimages/merchandise-icon.png", 16, 16);
		setWidth(525);
		setHeight(350);
		setTitle("PO Approval");
		VLayout contentLayout = new VLayout();
		contentLayout.setLayoutAlign(Alignment.CENTER);
		contentLayout.setLayoutTopMargin(40);
		contentLayout.setLayoutLeftMargin(40);
		VLayout mainLayout = new VLayout();
		LayoutSpacer spacer1 = new LayoutSpacer();
		spacer1.setHeight(10);
		LayoutSpacer spacer2 = new LayoutSpacer();
		spacer2.setHeight(25);
		HLayout formLayout = new HLayout();
		formLayout.setMembers(getForm());
		contentLayout.setMembers(getApprovePoLabel(), spacer1, formLayout);
		mainLayout.setLayoutRightMargin(40);
		mainLayout.setLayoutLeftMargin(40);
		mainLayout.setMembers(contentLayout, spacer2, getButtonLayout());
		addItem(mainLayout);
		setOkCancelCallback(okCancelCallback);
	}

	private DynamicForm getForm() {
		if (myForm == null) {
			ArrayList<FormItem> formFields = new ArrayList<FormItem>();
			formFields.add(getPrintPoCheckbox());
			formFields.add(getPrintPackAndShipSelector());
			formFields.add(getPrintStoreReceivingWorksheetSelector());
			formFields.add(getPrintTicketOrderReportCheckbox());
			formFields.add(getPrintTotalsByColorCheckbox());
			formFields.add(getPrintTotalsBySizeCheckbox());
			formFields.add(getPrintPrepackComponentInformationCheckbox());
			formFields.add(getPoApprovalList());
			myForm = new DynamicForm();
			myForm.setSynchronousValidation(true);
			myForm.setPadding(0);
			myForm.setDataSource(getPoApprovalDataSource());
			FormItem[] formFieldsArray = new FormItem[formFields.size()];
			formFieldsArray = formFields.toArray(formFieldsArray);
			myForm.setFields(formFieldsArray);
			myForm.addHiddenValidationErrorsHandler(new HiddenValidationErrorsHandler() {
				
				@Override
				public void onHiddenValidationErrors(HiddenValidationErrorsEvent event) {
					SC.say(event.getErrors().toString());
					}
			});
		}
		return myForm;
	}

	private DataSource getPoApprovalDataSource() {
		if (myPoApprovalDataSource == null) {
			myPoApprovalDataSource = DataSource.get(IslandPacificDSConstants.DATASOURCE_PoApproval);


		}
		return myPoApprovalDataSource;
	}

	private HLayout getButtonLayout() {
		if (myButtonLayout == null) {
	        IButton okButton=new IButton("OK");
	        okButton.addClickHandler(new ClickHandler() {
				@Override
				public void onClick(com.smartgwt.client.widgets.events.ClickEvent event) {
					doApprove();
				}
			});
	        okButton.setLayoutAlign(Alignment.LEFT);
	        okButton.setZIndex(0);
	        IButton cancelButton=new IButton("Cancel");

	        LayoutSpacer buttonSpacer = new LayoutSpacer();
	        buttonSpacer.setWidth(5);

	        cancelButton.addClickHandler(new ClickHandler() {
				@Override
				public void onClick(com.smartgwt.client.widgets.events.ClickEvent event) {
					doCancel();
				}
			});
	        cancelButton.setLayoutAlign(Alignment.LEFT);
			myButtonLayout = new HLayout();
			myButtonLayout.setWidth100();
			myButtonLayout.setAlign(Alignment.RIGHT);
			myButtonLayout.setLayoutAlign(Alignment.RIGHT);
			myButtonLayout.setMembers(okButton, buttonSpacer, cancelButton);
			
		}
		return myButtonLayout;
	}

	/**
	 * Get the PO's to be approved
	 * @return A list of PO Header records.
	 */
	public String[] getPoNumbers() {
		return myPoNumbers;
	}

	/**
	 * Establish the list of PO's to be approved
	 * @param poNumbers A list of PO Header records.
	 */
	public void setPoNumbers(String[] poNumbers) {
		myPoNumbers = poNumbers;
		getForm().setValue(PO_APPROVAL_FIELD_poList, poNumbers);
		updateApprovalTitle();
	}

	/**
	 * Establish a single PO to be approved
	 * @param poHeaderRecords A list of PO Header records.
	 */
	public void setPo(String poNumber) {
		String[] poList = new String[] {poNumber};
		setPoNumbers(poList);
	}

	/**
	 * Get the file group for this approval
	 * @return
	 */
	public int getFileGroupNumber() {
		return myFileGroupNumber;
	}

	/**
	 * Establish the file group for this approval
	 * @param fileGroupNumber
	 */
	public void setFileGroupNumber(int fileGroupNumber) {
		myFileGroupNumber = fileGroupNumber;
		getForm().setValue(PO_APPROVAL_FIELD_fileGroupNumber, fileGroupNumber);
	}

	/**
	 * Define the completion callback.
	 * @return
	 */
	public IpOkCancelCallback getOkCancelCallback() {
		return myOkCancelCallback;
	}

	/**
	 * Get the okCancel callback.
	 * @param okCancelCallback
	 */
	public void setOkCancelCallback(IpOkCancelCallback okCancelCallback) {
		myOkCancelCallback = okCancelCallback;
	}

	private void doApprove() {
		if (getForm().validate(true)) {
			DSRequest requestProperties = new DSRequest();
			String[] poNumbers = getPoNumbers();
			String prompt = null;
			if (poNumbers.length == 1) {
				prompt = "Approving blockout " + poNumbers[0];
			}
			else {
				prompt = "Approving selected blockouts";
			}
			requestProperties.setPrompt(prompt);

			getForm().saveData(new DSCallback() {
				@Override
				public void execute(DSResponse response, Object rawData, DSRequest request) {
					Record responseData = response.getData()[0];
					Record[] statusList = responseData.getAttributeAsRecordArray(PO_APPROVAL_FIELD_poStatusList);
					PoApprovalReviewDialog myReviewDialog = new PoApprovalReviewDialog(new IpOkCancelCallback() {
						@Override
						public void onOk() {
							doOk();
						}
						@Override
						public void onCancel() {
							doCancel();
						}
					});
					myReviewDialog.setPoApprovalStatusList(statusList);
					myReviewDialog.enable();
					myReviewDialog.centerInPage();
					myReviewDialog.show();
					myReviewDialog.bringToFront();
				}
			}, requestProperties);
		} 
	}
	
	private void doCancel() {
		hide();
		getOkCancelCallback().onCancel();
	}
	
	private void doOk() {
		hide();
		getOkCancelCallback().onOk();
	}

	public Label getApprovePoLabel() {
		if (myApprovePoLabel == null) {
			myApprovePoLabel = new Label();
			myApprovePoLabel.setStyleName("dialogTitle");
			myApprovePoLabel.setHeight(20);
		}
		return myApprovePoLabel;
	}
	
	private void updateApprovalTitle() {
		String[] poNumbers = getPoNumbers();
		String title = null;
		if (poNumbers == null || poNumbers.length > 1) {
			title = "Approve Selected Blockouts";
		}
		else {
			title = "Approve Blockout " + poNumbers[0];
		}
		getApprovePoLabel().setContents(title);
	}

	public CheckboxItem getPrintPoCheckbox() {
		if (myPrintPoCheckbox == null) {
			myPrintPoCheckbox = new CheckboxItem(PO_APPROVAL_FIELD_printPo);
			myPrintPoCheckbox.setLabelAsTitle(true);
			myPrintPoCheckbox.setEndRow(true);
			myPrintPoCheckbox.setWrapTitle(false);
			String printPoPreference = IPGui.ippoprfRecord.getAttribute("POPRAPR");
			if (printPoPreference.equalsIgnoreCase("N")) {
				myPrintPoCheckbox.setValue(false);
			}
			else {
				myPrintPoCheckbox.setValue(true);
			}
			if (printPoPreference.equalsIgnoreCase("E")) {
				myPrintPoCheckbox.setDisabled(true);
			}
			else {
				myPrintPoCheckbox.setDisabled(false);
			}
		}
		return myPrintPoCheckbox;
	}

	public SelectItem getPrintPackAndShipSelector() {
		if (myPrintPackAndShipSelector == null) {
			myPrintPackAndShipSelector = new SelectItem(PO_APPROVAL_FIELD_printPackAndShipReports);
			String packAndShipPreference = IPGui.ippoprfRecord.getAttribute("POPRPSR");
			myPrintPackAndShipSelector.setValue(packAndShipPreference);
			myPrintPackAndShipSelector.setEndRow(true);
			myPrintPackAndShipSelector.setWrapTitle(false);
		}
		return myPrintPackAndShipSelector;
	}

	public SelectItem getPrintStoreReceivingWorksheetSelector() {
		if (myPrintStoreReceivingWorksheetSelector == null) {
			myPrintStoreReceivingWorksheetSelector = new SelectItem(PO_APPROVAL_FIELD_printStoreRecievingWorksheet);
			String storeReceivingWorksheetPreference = IPGui.ippoprfRecord.getAttribute("POPRSRW");
			myPrintStoreReceivingWorksheetSelector.setValue(storeReceivingWorksheetPreference);
			myPrintStoreReceivingWorksheetSelector.setEndRow(true);
			myPrintStoreReceivingWorksheetSelector.setWrapTitle(false);
		}
		return myPrintStoreReceivingWorksheetSelector;
	}

	public TextItem getPoApprovalList() {
		if (myPoApprovalList == null) {
			myPoApprovalList = new TextItem(PO_APPROVAL_FIELD_poList);
			myPoApprovalList.setValue("");
//			myPoApprovalList.setVisible(false);
		}
		return myPoApprovalList;
	}

	public CheckboxItem getPrintTicketOrderReportCheckbox() {
		if (myPrintTicketOrderReportCheckbox == null) {
			myPrintTicketOrderReportCheckbox = new CheckboxItem(PO_APPROVAL_FIELD_printTicketOrderReport);
			boolean printTicketOrderReportPreference = IPGui.ippoprfRecord.getAttributeAsBoolean("POPRTOR");
			if (printTicketOrderReportPreference) {
				myPrintTicketOrderReportCheckbox.setValue(true);
			}
			else {
				myPrintTicketOrderReportCheckbox.setValue(false);
			}
			myPrintTicketOrderReportCheckbox.setLabelAsTitle(true);
			myPrintTicketOrderReportCheckbox.setEndRow(true);
			myPrintTicketOrderReportCheckbox.setWrapTitle(false);
		}
		return myPrintTicketOrderReportCheckbox;
	}

	public CheckboxItem getPrintTotalsByColorCheckbox() {
		if (myPrintTotalsByColorCheckbox == null) {
			myPrintTotalsByColorCheckbox = new CheckboxItem(PO_APPROVAL_FIELD_printTotalsByColor);
			boolean printTotalsByColorPreference = IPGui.ippoprfRecord.getAttributeAsBoolean("POPRTOTC");
			if (printTotalsByColorPreference) {
				myPrintTotalsByColorCheckbox.setValue(true);
			}
			else {
				myPrintTotalsByColorCheckbox.setValue(false);
			}
			myPrintTotalsByColorCheckbox.setLabelAsTitle(true);
			myPrintTotalsByColorCheckbox.setEndRow(true);
			myPrintTotalsByColorCheckbox.setWrapTitle(false);
		}
		return myPrintTotalsByColorCheckbox;
	}

	public CheckboxItem getPrintTotalsBySizeCheckbox() {
		if (myPrintTotalsBySizeCheckbox == null) {
			myPrintTotalsBySizeCheckbox = new CheckboxItem(PO_APPROVAL_FIELD_printTotalsBySize);
			boolean printTotalsBySizePreference = IPGui.ippoprfRecord.getAttributeAsBoolean("POPRTOTS");
			if (printTotalsBySizePreference) {
				myPrintTotalsBySizeCheckbox.setValue(true);
			}
			else {
				myPrintTotalsBySizeCheckbox.setValue(false);
			}
			myPrintTotalsBySizeCheckbox.setLabelAsTitle(true);
			myPrintTotalsBySizeCheckbox.setEndRow(true);
			myPrintTotalsBySizeCheckbox.setWrapTitle(false);
		}
		return myPrintTotalsBySizeCheckbox;
	}

	public CheckboxItem getPrintPrepackComponentInformationCheckbox() {
		if (myPrintPrepackComponentInformationCheckbox == null) {
			myPrintPrepackComponentInformationCheckbox = new CheckboxItem(PO_APPROVAL_FIELD_printPrepackComponentInformation);
			myPrintPrepackComponentInformationCheckbox.setValue(IPGui.ippoprfRecord.getAttributeAsBoolean("POPRPPKI"));
			myPrintPrepackComponentInformationCheckbox.setLabelAsTitle(true);
			myPrintPrepackComponentInformationCheckbox.setEndRow(true);
			myPrintPrepackComponentInformationCheckbox.setWrapTitle(false);
		}
		return myPrintPrepackComponentInformationCheckbox;
	}
	
}
