
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
// Edit Database Record using client-side dialog with properties grid
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//


// Refresh dialog with these saved values (from when dialog was opened)
var LastEditRecordObjectDataType = null;
var LastEditRecordObjectTable = null;
var LastEditRecordObjectRecordId = null;
var LastEditRecordSelectedCellTable = null;
var LastEditRecordSelectedCellColumnId = null;
var LastEditRecordIsNew = null;
var LastEditRecordSaveClicked = false;
var LastEditRecordDeleteClicked = false;


//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
// Open the Edit Record dialog
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
var bEditRecordDialogIsOpen = false;
function OpenEditRecordDialog(bNewRecord, ObjectDataType, ObjectTable, ObjectRecordId, SelectedCellTable, SelectedCellColumnId) {

    // Open the user Edit Record dialog
    // See: DialogEditRecord.cshtml

    // These parameters tell the property grid what to display
    // Examples:
    //          stdata.BaseDataSet
    //          wipdata.wipitem
    //          radata.raitem
    if (!ObjectDataType || !ObjectTable || !ObjectRecordId)
        return;

    // Remember these to refresh this dialog
    LastEditRecordObjectDataType = ObjectDataType;
    LastEditRecordObjectTable = ObjectTable;
    LastEditRecordObjectRecordId = ObjectRecordId;
    LastEditRecordSelectedCellTable = SelectedCellTable;
    LastEditRecordSelectedCellColumnId = SelectedCellColumnId;
    LastEditRecordIsNew = bNewRecord;
    LastEditRecordSaveClicked = false;
    LastEditRecordDeleteClicked = false;

    // Fill the property grid in the dialog with record properties
    ActivePropertyGridPartialViewDivId = "igDialogEditRecordPropertiesDiv";
    AjaxRefreshPropertyGridView($("#igDialogEditRecordPropertiesDiv"), "OBJECT", ObjectDataType, ObjectTable, ObjectRecordId, SelectedCellTable, SelectedCellColumnId, ""/*PropertyValuesJsonString*/);
    AddPropertiesGridToContentArray(ObjectDataType, ObjectTable, ObjectRecordId, SelectedCellTable, SelectedCellColumnId);


    var nDlgWidth = 600;
    var nDlgHeight = 800;
    var nWindowWidth = $(window).width();
    var nWindowHeight = $(window).height();
    if (nWindowWidth < nDlgWidth)
        nDlgWidth = nWindowWidth * 0.98;
    if (nWindowHeight < nDlgHeight)
        nDlgHeight = nWindowHeight * 0.95;

    // Open the dialog
    // igniteui.com/help/igdialog-property-reference
    $("#igDialogEditRecord").igDialog({ modal: true, headerText: "Edit Record", width: nDlgWidth, height: nDlgHeight, resizable: false, closeOnEscape: true, openAnimation: "", closeAnimation: "fade", stateChanged: function (event, ui) { OnEditRecordStateChanged(event, ui); }/*, openAnimation: "fade"*/ });
    $("#igDialogEditRecord").igDialog("open");

    //ResizeDialogToWindowSize("igDialogEditRecord");
    CenterDialog("igDialogEditRecord");

    // Set up controls
    bEditRecordDialogIsOpen = true;

    // OK button click
    $("#igDialogEditRecordOKButton").unbind().click(function () {

        // Only close dialog if the record can be saved
        // proceedcallback will be called, which closes dialog
        AjaxCanSaveContentRecord(LastEditRecordObjectDataType, LastEditRecordObjectTable, LastEditRecordObjectRecordId, OnEditRecordOkBtnClicked/*proceedcallback*/, true/*proceedobject*/);
    });

    // Delete button click
    $("#igDialogEditRecordDeleteButton").unbind().click(function () {
        LastEditRecordDeleteClicked = true;
        CloseEditRecordDialog();

        // Ask to delete the record
        AjaxExecuteDeleteMenuCmd(ObjectDataType, ObjectTable, ObjectRecordId);
    });

}


/**
 * Callback, called when user clicks OK to save a record
 * Only called if the record can be saved
 * Actually, the record has already been saved
 * */
function OnEditRecordOkBtnClicked(bCloseDialog) {

    // Save button was clicked
    LastEditRecordSaveClicked = true;

    if (bCloseDialog)
        CloseEditRecordDialog();

    // Refresh
    SetSelectRecordIdAfterRebuild(LastEditRecordObjectTable, LastEditRecordObjectRecordId);
    RefreshSelectedContent();
}


function OnEditRecordStateChanged(event, ui) {

    if (!ui)
        return;
    if (!ui.action)
        return;

    // Close event
    if (ui.action == 'close') {

        // Closed dialog without saving the newly created record, so delete it
        if (LastEditRecordIsNew) {

            var bCloseButton = (ui.button == 'close');

            // This record was newly created for this edit dialog
            // It is not and existing record that was being edited
            // Delete newly created records if the dialog was closed by the "X" button (not Save or Delete buttons)
            //if (!LastEditRecordSaveClicked && !LastEditRecordDeleteClicked) {
            if (bCloseButton) {
                AjaxDeleteContentRecord(LastEditRecordObjectDataType, LastEditRecordObjectTable, LastEditRecordObjectRecordId);
                RefreshSelectedContent();
            }
        }

        // No longer open
        bEditRecordDialogIsOpen = false;
        ActivePropertyGridPartialViewDivId = "PropertyGridPartialViewDivId";

        // No longer used
        LastEditRecordObjectDataType = "";
        LastEditRecordObjectTable = "";
        LastEditRecordObjectRecordId = "";
    }
}





function CheckRefreshEditRecordDialog() {

    if (!bEditRecordDialogIsOpen)
        return false;

    var PropertiesDiv = $("#igDialogEditRecordPropertiesDiv");
    if (!PropertiesDiv || !PropertiesDiv.length)
        return false;

    // Refresh with the last saved values
    AjaxRefreshPropertyGridView($("#igDialogEditRecordPropertiesDiv"), "OBJECT", LastEditRecordObjectDataType, LastEditRecordObjectTable, LastEditRecordObjectRecordId, LastEditRecordSelectedCellTable, LastEditRecordSelectedCellColumnId, ""/*PropertyValuesJsonString*/);
    return true;
}


/**
 * Create a new Standard Time database record by this table type
 * Examples:
 *           "Projects" creates a new project
 *           "Tasks" creates a new time log
 * @param {any} ObjectTable
 */
function AjaxCreateNewDatabaseRecord(ObjectTable, DateString) {

    if (!ObjectTable)
        return;

    // Use selection and filter choices to create new records
    var ContentType = GetSelectedContentType();
    var SelectedRecordId = GetSelectedRecordId();
    var SelectedTableId = GetSelectedRecordTableId();
    var SelectedDataType = GetSelectedDataType();
    var FilterJsonString = GetSelectedContentPaneFilterJsonString();
    var SettingsJsonString = GetSelectedContentPaneSettingsJsonString();

    var data = {
        ContentType: ContentType,
        ObjectTable: ObjectTable,
        SelectedDataType: SelectedDataType,
        SelectedTableId: SelectedTableId,
        SelectedRecordId: SelectedRecordId,
        FilterJsonString: FilterJsonString,
        SettingsJsonString: SettingsJsonString,
        DateString: DateString,
    };

    console.log("AjaxCreateNewDatabaseRecord: " + ContentType + ", " + ObjectTable);

    $.ajax({
        url: VirtualDirectory + "/Home/AjaxCreateNewDatabaseRecord",
        type: "POST",
        data: JSON.stringify(data),
        dataType: "json",
        contentType: "application/json",
        success: function (response) {
            if (response.Success) {

                // "Your user rights do not allow access. Check with your administrator. (Access to Project Task view)"
                if (response.PromptNoAccess) {
                    PopupErrorMessage(response.PromptTitle, response.PromptMessage);
                    return;
                }

                // Edit the new record
                OpenEditRecordDialog(true/*bNewRecord*/, response.ObjectDataType, response.ObjectTable, response.ObjectRecordId);
            }
            else {
                ToastError("AjaxCreateNewDatabaseRecord", response.ErrorResults);
            }
        },
        error: function (xhr, status, error) {
            var errormsg = "Error " + xhr.status + ", " + xhr.statusText;
            ToastError("AjaxCreateNewDatabaseRecord", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });
}






function OnCreateNewContentRecord(DateString) {

    // Add a new record for this content type
    var ContentType = GetSelectedContentType();
    if (!ContentType) {
        ToastError("Add Content", "Choose an icon from Home (All Views) to add a record");
        return;
    }

    // Call Ajax to create a new record of this content type
    // Then open a dialog to edit it
    AjaxCreateNewContentRecord(ContentType, DateString);
}


function AjaxCreateNewContentRecord(ContentType, DateString) {

    // Check values
    if (!ContentType)
        return;

    // Use selection and filter choices to create new records
    var SelectedRecordId = GetSelectedRecordId();
    var SelectedTableId = GetSelectedRecordTableId();
    var SelectedDataType = GetSelectedDataType();
    var SelectedColumnId = GetSelectedColumnId();
    var FilterJsonString = GetSelectedContentPaneFilterJsonString();
    var SettingsJsonString = GetSelectedContentPaneSettingsJsonString();

    var params = {
        ContentType: ContentType,
        SelectedDataType: SelectedDataType,
        SelectedTableId: SelectedTableId,
        SelectedRecordId: SelectedRecordId,
        SelectedColumnId: SelectedColumnId,
        FilterJsonString: FilterJsonString,
        SettingsJsonString: SettingsJsonString,
        DateString: DateString,
    };

    //console.log("AjaxCreateNewContentRecord: " + ContentType);

    $.ajax({
        url: VirtualDirectory + "/Home/AjaxCreateNewContentRecord",
        type: "POST",
        data: JSON.stringify(params),
        contentType: "application/json",
        success: function (response) {
            if (response.Success) {

                // "Your user rights do not allow access. Check with your administrator. (Access to Project Task view)"
                if (response.PromptNoAccess) {
                    PopupErrorMessage(response.PromptTitle, response.PromptMessage);
                    return;
                }

                // Prompt for license code, then create new recordset
                if (response.PromptForValue) {
                    PromptForValueThenCreateNewContentRecord(ContentType, response.PromptTitle, response.PromptMessage);
                    return;
                }

                // Edit the new record
                if (response.ObjectDataType && response.ObjectTable && response.ObjectRecordId) {
                    //console.log("AjaxCreateNewContentRecord, OpenEditRecordDialog: " + response.ObjectDataType + ", " + response.ObjectTable + ", " + response.ObjectRecordId);
                    OpenEditRecordDialog(true/*bNewRecord*/, response.ObjectDataType, response.ObjectTable, response.ObjectRecordId);
                    return;
                }

                ToastError("Create New Content", "Something went wrong: " + ContentType);
            }
            else {
                ToastError("Create New Content", response.ErrorResults + ": " + ContentType);
            }
        },
        error: function (xhr, status, error) {
            var errormsg = "Error " + xhr.status + ", " + xhr.statusText;
            ToastError("AjaxCreateNewContentRecord", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });

}



function AjaxCreateNewContentRecordFromObjectType(ObjectType) {

    if (!ObjectType)
        return;

    var params = {
        ObjectType: ObjectType,
    };

    $.ajax({
        url: VirtualDirectory + "/Home/AjaxGetContentTypeFromObjectType",
        type: "POST",
        data: JSON.stringify(params),
        contentType: "application/json",
        success: function (response) {
            if (response.Success) {

                if (response.ContentType)
                    AjaxCreateNewContentRecord(response.ContentType);
                else
                    ToastError("No ContentType for object type: ", response.ErrorResults + ": " + ObjectType);
            }
            else {
                ToastError("Create New Content", response.ErrorResults + ": " + ObjectType);
            }
        },
        error: function (xhr, status, error) {
            var errormsg = "Error " + xhr.status + ", " + xhr.statusText;
            ToastError("AjaxCreateNewContentRecordFromObjectType", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });
}



// Use when creating content recordset from prompted value (below)
var PromptForValueContentType;

/**
 * Prompt for a value, then create a new content recordset
 * Example:
 *     Prompt for a license code, then add it to the database
 * @param {any} ContentType
 * @param {any} PromptTitle
 * @param {any} PromptMessage
 */
function PromptForValueThenCreateNewContentRecord(ContentType, PromptTitle, PromptMessage) {

    // Remember this for later
    PromptForValueContentType = ContentType;

    // Prompt for a new folder name
    var proceedcallback = AjaxCreateNewContentRecordWithPromptValue;
    var proceedobject = null;
    PopupPromptForValueBox(PromptTitle, PromptMessage, "", proceedcallback, proceedobject);
}

/**
 * Callback after prompting for a recordset value
 * Used to create a new recordset from a user-entered value
 * Example:
 *     Prompt for a license code, then add it to the database
 * @param {any} prompt
 */
function AjaxCreateNewContentRecordWithPromptValue(prompt) {

    // Check values
    if (!PromptForValueContentType)
        return;
    if (!prompt)
        return;
    if (!prompt.sValue)
        return;

    // Use selection and filter choices to create new records
    var SelectedRecordId = GetSelectedRecordId();
    var SelectedTableId = GetSelectedRecordTableId();
    var SelectedDataType = GetSelectedDataType();
    var SelectedColumnId = GetSelectedColumnId();
    var FilterJsonString = GetSelectedContentPaneFilterJsonString();
    var SettingsJsonString = GetSelectedContentPaneSettingsJsonString();

    var params = {
        ContentType: PromptForValueContentType,
        SelectedDataType: SelectedDataType,
        SelectedTableId: SelectedTableId,
        SelectedRecordId: SelectedRecordId,
        SelectedColumnId: SelectedColumnId,
        PromptValue: prompt.sValue,
        FilterJsonString: FilterJsonString,
        SettingsJsonString: SettingsJsonString,
    };

    $.ajax({
        url: VirtualDirectory + "/Home/AjaxCreateNewContentRecordWithPromptValue",
        type: "POST",
        data: JSON.stringify(params),
        contentType: "application/json",
        success: function (response) {
            if (response.Success) {

                // Good value?
                if (response.PromptTitle && response.PromptMessage) {
                    if (response.InvalidPrompt)
                         PopupErrorMessage(response.PromptTitle, response.PromptMessage);
                    else PopupInfoMessage(response.PromptTitle, response.PromptMessage);
                }

                // Open an edit dialog or just refresh the content to show the new record?
                if (response.NoEditDialog) {
                    SetSelectRecordIdAfterRebuild(response.ObjectTable, response.ObjectRecordId);
                    RefreshSelectedContent();
                    return;
                }

                // Edit the new record
                if (response.ObjectDataType && response.ObjectTable && response.ObjectRecordId) {
                    OpenEditRecordDialog(true/*bNewRecord*/, response.ObjectDataType, response.ObjectTable, response.ObjectRecordId);
                    return;
                }

                ToastError("New Content With Prompt", "Something went wrong: " + ContentType);
            }
            else {
                ToastError("New Content With Prompt", response.ErrorResults + ": " + ContentType);
            }
        },
        error: function (xhr, status, error) {
            var errormsg = "Error " + xhr.status + ", " + xhr.statusText;
            ToastError("AjaxCreateNewContentRecord", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });
}



function AjaxDeleteContentRecord(ContentType, TableId, RecordId, proceedcallback, proceedobject) {

    if (!TableId)
        return;
    if (!RecordId)
        return;

    var data = {
        ContentType: ContentType,
        TableId: TableId,
        RecordId: RecordId,
    };

    $.ajax({
        url: VirtualDirectory + "/Home/AjaxDeleteContentRecord",
        type: "POST",
        data: JSON.stringify(data),
        dataType: "json",
        contentType: "application/json",
        success: function (response) {
            if (response.Success) {

                // Delete was successful, now close the edit dialog box
                if (proceedcallback)
                    proceedcallback(proceedobject);
            }
            else {
                ToastError("AjaxDeleteContentRecord", response.ErrorResults);
            }
        },
        error: function (xhr, status, error) {
            var errormsg = "Error " + xhr.status + ", " + xhr.statusText;
            ToastError("AjaxDeleteContentRecord", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });
}



function AjaxCanSaveContentRecord(ContentType, TableId, RecordId, proceedcallback, proceedobject) {

    if (!TableId)
        return;
    if (!RecordId)
        return;

    var data = {
        ContentType: ContentType,
        TableId: TableId,
        RecordId: RecordId,
    };

    $.ajax({
        url: VirtualDirectory + "/Home/AjaxCanSaveContentRecord",
        type: "POST",
        data: JSON.stringify(data),
        dataType: "json",
        contentType: "application/json",
        success: function (response) {
            if (response.Success) {

                // The record can be saved, now close the edit dialog box
                if (response.CanSaveRecord) {
                    if (proceedcallback)
                        proceedcallback(proceedobject);
                }
                else if (response.CanSaveErrorMsg) {
                    // Cannot save, display error message
                    PopupErrorMessage("Save Record", response.CanSaveErrorMsg)
                }
            }
            else {
                ToastError("AjaxCanSaveContentRecord", response.ErrorResults);
            }
        },
        error: function (xhr, status, error) {
            var errormsg = "Error " + xhr.status + ", " + xhr.statusText;
            ToastError("AjaxCanSaveContentRecord", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });
}



//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
// Create new database records
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//


function CreateNewTimelogRecord() {
    AjaxCreateNewDatabaseRecord("Tasks");
}

function CreateNewProjectRecord() {
    AjaxCreateNewDatabaseRecord("Projects");
}

function CreateNewClientRecord() {
    AjaxCreateNewDatabaseRecord("Clients");
}

function CreateNewProjectTaskRecord() {
    AjaxCreateNewDatabaseRecord("ProjectTasks");
}

function CreateNewUserRecord() {
    AjaxCreateNewDatabaseRecord("Users");
}

function CreateNewCategoryRecord() {
    AjaxCreateNewDatabaseRecord("Categories");
}

function CreateNewExpenseRecord() {
    AjaxCreateNewDatabaseRecord("Expenses");
}

function CreateNewExpenseTemplateRecord() {
    AjaxCreateNewDatabaseRecord("ExpenseTemplates");
}

function CreateNewTimeOffRecord() {
    AjaxCreateNewDatabaseRecord("TimeOff");
}

function CreateNewInvoiceRecord() {
    AjaxCreateNewDatabaseRecord("Invoices");
}




//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
// Close the Edit Record dialog
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
function CloseEditRecordDialog() {
    $("#igDialogEditRecord").igDialog("close");
    bEditRecordDialogIsOpen = false;
    ActivePropertyGridPartialViewDivId = "PropertyGridPartialViewDivId";
}

function IsEditRecordDialogOpen() {
    return bEditRecordDialogIsOpen;
}




//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//


/**
 * Check to see if the current "logged in" user has a certain right
 * Use callbacks to proceed to the next step if the user has the right and if no right
 * Callbacks make this function somewhat synchronous because users can't proceed until this function completes
 * @param {any} UserRight
 * @param {any} bDisplayError
 * @param {any} hasrightcallback
 * @param {any} hasrightobject
 * @param {any} norightcallback
 * @param {any} norightobject
 * @returns
 */
function AjaxLoggedInUserHasRight(UserRight, bDisplayError, hasrightcallback, hasrightobject, norightcallback, norightobject) {

    if (!UserRight)
        return;

    var params = {
        "UserRight": UserRight,
    };

    $.ajax({
        url: VirtualDirectory + "/Home/AjaxLoggedInUserHasRight",
        type: "POST",
        data: JSON.stringify(params),
        contentType: "application/json",
        success: function (response) {

            if (response.Success && response.HasRight) {
                if (hasrightcallback)
                    hasrightcallback(hasrightobject);
            }
            else {
                // User does not have this right
                if (norightcallback)
                    norightcallback(norightobject);

                if (bDisplayError) {
                    PopupMessageBox(response.PromptTitle, response.PromptMessage);
                }
            }
        },
        error: function (xhr, status, error) {
            var errormsg = "Error " + xhr.status + ", " + xhr.statusText + "\r\nText: " + sAiChatText;
            (window.opener || window).ToastError("AjaxLoggedInUserHasRight", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });
}




function AjaxLoggedInUserHasFeature(UserFeature, bDisplayError, hasfeaturecallback, hasfeatureobject, nofeaturecallback, nofeatureobject) {

    if (!UserFeature)
        return;

    var params = {
        "UserFeature": UserFeature,
    };

    $.ajax({
        url: VirtualDirectory + "/Home/AjaxLoggedInUserHasFeature",
        type: "POST",
        data: JSON.stringify(params),
        contentType: "application/json",
        success: function (response) {

            if (response.Success && response.HasFeature) {
                if (hasfeaturecallback)
                    hasfeaturecallback(hasfeatureobject);
            }
            else {
                // User does not have this feature
                if (nofeaturecallback)
                    nofeaturecallback(nofeatureobject);

                if (bDisplayError) {
                    PopupMessageBox(response.PromptTitle, response.PromptMessage);
                }
            }
        },
        error: function (xhr, status, error) {
            var errormsg = "Error " + xhr.status + ", " + xhr.statusText + "\r\nText: " + sAiChatText;
            (window.opener || window).ToastError("AjaxLoggedInUserHasFeature", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });
}




