package com.smartgwt.sample.client;

import com.google.gwt.core.client.EntryPoint;
import com.smartgwt.client.core.KeyIdentifier;
import com.smartgwt.client.data.Criteria;
import com.smartgwt.client.data.DSRequest;
import com.smartgwt.client.data.DataSource;
import com.smartgwt.client.data.Record;
import com.smartgwt.client.data.SortSpecifier;
import com.smartgwt.client.types.DSOperationType;
import com.smartgwt.client.types.SortDirection;
import com.smartgwt.client.util.EventHandler;
import com.smartgwt.client.util.Page;
import com.smartgwt.client.util.PageKeyHandler;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.IButton;
import com.smartgwt.client.widgets.Label;
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.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.grid.events.RecordClickEvent;
import com.smartgwt.client.widgets.grid.events.RecordClickHandler;
import com.smartgwt.client.widgets.layout.VStack;
import com.smartgwt.client.widgets.toolbar.ToolStrip;
import com.smartgwt.client.widgets.viewer.DetailViewer;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class HibernateSpringDMI implements EntryPoint {

    private ListGrid     boundList;
    private DynamicForm  boundForm;
    private IButton      saveBtn;
    private DetailViewer boundViewer;

    // circumvent GWT 1.5.3 issue
    // see http://code.google.com/p/google-web-toolkit/issues/detail?id=3247
    private static volatile Object unTightenableObject    = new Object();
    private static volatile String stringThatPinsToString = unTightenableObject.toString();

    /**
     * This is the entry point method.
     */
    public void onModuleLoad() {

        final KeyIdentifier debugKey = new KeyIdentifier();
        debugKey.setCtrlKey(true);
        debugKey.setKeyName("D");

        Page.registerKey(debugKey, new PageKeyHandler() {

            @Override
            public void execute(final String keyName) {
                SC.showConsole();
            }
        });

        final DataSource dataSource = DataSource.get("supplyItemSpringDMI");

        final VStack vStack = new VStack();
        vStack.setLeft(175);
        vStack.setTop(75);
        vStack.setWidth("70%");
        vStack.setMembersMargin(20);

        final Label label = new Label();
        label.setContents("<ul>" + "<li>click a record in the grid to view and edit that record in the form</li>"
                + "<li>click <b>New</b> to start editing a new record in the form</li>"
                + "<li>click <b>Save</b> to save changes to a new or edited record in the form</li>"
                + "<li>click <b>Clear</b> to clear all fields in the form</li>"
                + "<li>click <b>Filter</b> to filter (substring match) the grid based on form values</li>"
                + "<li>click <b>Fetch</b> to fetch records (exact match) for the grid based on form values</li>"
                + "<li>double-click a record in the grid to edit inline (press Return, or arrow/tab to another record, to save)</li>" + "</ul>");
        vStack.addMember(label);

        boundList = new ListGrid();
        boundList.setHeight(200);
        boundList.setCanEdit(true);
        boundList.setDataSource(dataSource);

        boundList.addRecordClickHandler(new RecordClickHandler() {

            @Override
            public void onRecordClick(final RecordClickEvent event) {
                final Record record = event.getRecord();
                boundForm.editRecord(record);
                saveBtn.enable();
                boundViewer.viewSelectedData(boundList);
            }
        });
        boundList.addKeyPressHandler(keyPressEvent -> {
            if (keyPressEvent.isCtrlKeyDown() && "Z".equals(EventHandler.getKey())) {
                performUndo();
            }
        });
        vStack.addMember(boundList);

        boundForm = new DynamicForm();
        boundForm.setDataSource(dataSource);
        boundForm.setNumCols(6);
        boundForm.setAutoFocus(false);
        vStack.addMember(boundForm);

        final ToolStrip toolbar = new ToolStrip();
        toolbar.setMembersMargin(10);
        toolbar.setHeight(22);

        saveBtn = new IButton("Save");
        saveBtn.addClickHandler(new ClickHandler() {

            @Override
            public void onClick(final ClickEvent event) {
                boundForm.saveData();
                if (!boundForm.hasErrors()) {
                    boundForm.clearValues();
                    saveBtn.disable();
                }
            }
        });
        toolbar.addMember(saveBtn);

        final IButton clearBtn = new IButton("Clear");
        clearBtn.addClickHandler(new ClickHandler() {

            @Override
            public void onClick(final ClickEvent event) {
                boundForm.clearValues();
                saveBtn.disable();
            }
        });
        toolbar.addMember(clearBtn);

        final IButton filterBtn = new IButton("Filter");
        filterBtn.addClickHandler(new ClickHandler() {

            @Override
            public void onClick(final ClickEvent event) {
                boundList.filterData(boundForm.getValuesAsCriteria());
                saveBtn.disable();
            }
        });
        toolbar.addMember(filterBtn);

        final IButton fetchBtn = new IButton("Fetch");
        fetchBtn.addClickHandler(new ClickHandler() {

            @Override
            public void onClick(final ClickEvent event) {
                boundList.fetchData(boundForm.getValuesAsCriteria());
                saveBtn.disable();
            }
        });
        toolbar.addMember(fetchBtn);

        final IButton deleteBtn = new IButton("Delete");
        deleteBtn.addClickHandler(new ClickHandler() {

            @Override
            public void onClick(final ClickEvent event) {
                boundList.removeSelectedData();
                boundList.deselectAllRecords();
            }
        });
        toolbar.addMember(deleteBtn);

        vStack.addMember(toolbar);

        boundViewer = new DetailViewer();
        boundViewer.setDataSource(dataSource);
        vStack.addMember(boundViewer);

        vStack.draw();

        boundList.filterData(null);
    }

    private void performUndo() {

        final DataSource gridDataSource = boundList.getDataSource();
        final String auditDataSourceId = "audit_" + gridDataSource.getID();

        final String primaryKeyName = gridDataSource.getPrimaryKeyFieldName();
        final Criteria contactCriteria = new Criteria();
        // TODO this has to be committed contactCriteria.addCriteria("audit_modifier", auditModifier);
        final DSRequest properties = new DSRequest();
        final SortSpecifier sortByversion = new SortSpecifier("audit_revision", SortDirection.DESCENDING);
        final SortSpecifier[] sorting = new SortSpecifier[0];
        sorting[0] = sortByversion;
        properties.setSortBy(sorting);
        // This is to fetch the top most row with highest audit_revision number, which means the latest change done by user
        properties.setStartRow(0);
        properties.setEndRow(2);
        final DataSource auditDS = DataSource.get(auditDataSourceId);
        if (null != auditDS) {
            auditDS.fetchData(contactCriteria, (final com.smartgwt.client.data.DSResponse dsResponse, final Object data, final DSRequest dsRequest) -> {
                if ((dsResponse.getData() != null) && (dsResponse.getData().length > 0)) {
                    final Record currentAuditRecord = dsResponse.getData()[0];
                    final String primaryKeyValInAudit = currentAuditRecord.getAttribute(primaryKeyName);
                    final String operationType = currentAuditRecord.getAttributeAsString("audit_operationType");
                    final DSRequest auditActionProperties = new DSRequest();

                    if (DSOperationType.UPDATE.getValue().equals(operationType) && (dsResponse.getData().length > 1)) {
                        final Record lastAuditRecord = dsResponse.getData()[1];
                        final Record changedRecord = boundList.getResultSet().find(primaryKeyName, primaryKeyValInAudit);
                        boundList.getRecordIndex(changedRecord);
                        if (lastAuditRecord.getAttribute(primaryKeyName).equals(primaryKeyValInAudit)) {
                            final Object[] fieldsChangedObj = (Object[]) currentAuditRecord.getAttributeAsObject("audit_changedFields");
                            for (final Object fieldChangedObj : fieldsChangedObj) {
                                changedRecord.setAttribute(fieldChangedObj.toString(), lastAuditRecord.getAttribute(fieldChangedObj.toString()));
                            }
                            auditActionProperties.setOperationId("auditUpdate");
                            gridDataSource.updateData(changedRecord, (response, obj, request) -> boundList.refreshRow(boundList.getRecordIndex(changedRecord)),
                                    auditActionProperties);
                        }

                    } else if (DSOperationType.ADD.getValue().equals(operationType)) {
                        final Record changedRecord = boundList.getResultSet().find(primaryKeyName, primaryKeyValInAudit);
                        final int rowNum = boundList.getRowNum(new ListGridRecord(changedRecord));
                        auditActionProperties.setOperationId("auditRemove");
                        gridDataSource.removeData(boundList.getRecord(rowNum),
                                (response, obj, request) -> boundList.refreshRow(boundList.getRecordIndex(changedRecord)), auditActionProperties);

                    } else if (DSOperationType.REMOVE.getValue().equals(operationType)) {
                        currentAuditRecord.setAttribute(primaryKeyName, (String) null);
                        auditActionProperties.setOperationId("auditAdd");
                        gridDataSource.addData(currentAuditRecord, (response, obj, request) -> boundList.refreshData(), auditActionProperties);
                    }
                    // This remove is for the actual Audit entry which was created by User's action. This remove can be considered similar to a Stack Pop
                    // action.
                    auditDS.removeData(currentAuditRecord);

                } else {
                    SC.say("can not perform undo");
                }

            }, properties);
        } else {
            SC.say("undo");
        }

    }

}
