﻿//***************************************************************************
//dAloor created on 07Sept2016
//Helper script file for all clone related activites 
//***************************************************************************

var IOTAP_AddOn_RecordClone_cloneRoleId = "IOTAP Record Clone (Single)";
var IOTAP_AddOn_RecordClone_multiCloneRoleId = "IOTAP Record Clone (Multi)";
var apiVersion = "v8.0";

var IOTAP_AddOn_RecordClone_ClonePrompt = false;
var IOTAP_AddOn_RecordClone_OpenCloneRecord = false;
var IOTAP_AddOn_RecordClone_CloneMultiple = false;
var cloneEnabledEntities;
var userRoles;
                   
//Function to trigger clone from ribbon button
//Works for both Clone/MultiClone from both Form/Grid
IOTAP_AddOn_RecordClone_TriggerRecordClone = function (entityName, entityId, buttonName, control)
{
    var countOfClones = 1;
    try {

        entityId = String( entityId );       

        if ( buttonName == "clone" )
        {                
            //if multiple records selected for single clone
            if ( entityId.indexOf( "," ) > 0 && IOTAP_AddOn_RecordClone_CloneMultiple == false ) {
                Xrm.Utility.alertDialog( 'This entity is not configured for multiple record cloning.' );
                return;
            }                                                                                      
        }

        if ( buttonName == "multiclone" ) {
            countOfClones = prompt( "Number of clones to be created", '' );

            if ( isNaN( parseInt( countOfClones ) ) || countOfClones == null || ( !isNaN( countOfClones ) && ( parseInt( countOfClones ) < 1 || parseInt( countOfClones ) > 50 ) ) ) {
                Xrm.Utility.alertDialog( 'Invalid entry! Please enter a number between 1 to 50' );
                return;
            }
        }

        var processClone = true;

        if ( IOTAP_AddOn_RecordClone_ClonePrompt ) {
            Xrm.Utility.confirmDialog( "Are you sure you want to create a Clone?", function ()
            {
                processClone = true;

            }, function ()
            {
                processClone = false;
            } );
        }
                
        if ( processClone ) {
            IOTAP_AddOn_RecordClone_ShowProgressBar( "Cloning...." );
                                              
            setTimeout( function ()
            {
                try {

                    var loggedInUser = new Object();
                    loggedInUser["systemuserid"] = Xrm.Page.context.getUserId();
                    loggedInUser["@odata.type"] = "Microsoft.Dynamics.CRM.systemuser";

                    ////Call the Action to create the clone record
                    var cloneActionName = "iotap_recordclone";
                    var cloneActionParameters = {
                        "EntitySchemaName": String( entityName ),
                        "RecordId": String( entityId ),
                        "NoOfClone": parseInt( countOfClones ),
                        "UserId": loggedInUser
                    };
                
                    var cloneId = IOTAP_AddOn_RecordClone_CallCustomAction( cloneActionName, cloneActionParameters );
               
                    //If clone is invoked from grid
                    if ( typeof ( control ) != "undefined" ) {
                        control.refresh();
                    }

                    IOTAP_AddOn_RecordClone_HideProgressBar();                
               
                    if (IOTAP_AddOn_RecordClone_OpenCloneRecord && cloneId != "" && cloneId.indexOf(",") == -1)
                        Xrm.Utility.openEntityForm(entityName,cloneId);  
                }
                catch (ex) {                    
                    IOTAP_AddOn_RecordClone_HideProgressBar();
                    alert("ERROR : IOTAP RecordClone [" + ex + "]");
                }

            }, 100 );
        }
        
    }
    catch(ex)
    { 
        IOTAP_AddOn_RecordClone_HideProgressBar();
        alert( "ERROR : IOTAP RecordClone [" + ex.message + "]" );
    }
}               

 //Calls a custom action
IOTAP_AddOn_RecordClone_CallCustomAction = function(actionName, actionParams)
{
    try
    {         
        var httpReq = IOTAP_AddOn_RecordClone_CreateHTTPRequest( "POST", actionName, false );
        httpReq.send( JSON.stringify( actionParams ) );       
        data = JSON.parse(httpReq.responseText);

        if ( httpReq.status == 200 ) {
            //return back clone id in case of single clone
            if ( data.CloneId.indexOf( "," ) > 0 )
                return "";
            else
                return data.CloneId;
        }
        else
        {  
            throw String(data.error.message);
        }
    }
    catch ( ex ) {
        throw ex;
    }
}   

//Hide the Progress Bar
IOTAP_AddOn_RecordClone_HideProgressBar = function()
{
    window.top.parent.$( "body" ).find( "#progressBar" ).remove();
}

//Get the CRM Client Url
IOTAP_AddOn_RecordClone_GetClientUrl = function ()
{
    return Xrm.Page.context.getClientUrl();
}

//Display the Progress Bar
IOTAP_AddOn_RecordClone_ShowProgressBar = function(loadingMsg)
{
    try {

        var progressBar = "<div id='progressBar'style='width: 400px; height: 160px; top:42%; left:36%; display: block; position: fixed; margin:auto; z-index: 9999; vertical-align:middle; border:solid; border-width:2px'><table style='width: 100%; height: 100%; background-color:#ffffee'><tr><td align='center' style='vertical-align: middle; font-size:18px; font-weight:normal; font-family:calibri'><img src='" + IOTAP_AddOn_RecordClone_GetClientUrl() + "/WebResources/iotap_addon_recordclone_loading.gif'/><br/>" + loadingMsg + "</td></tr></table></div>";
        window.top.parent.$( "body" ).append( progressBar );
    }
    catch(ex)
    {
        throw ex;
    }
}

//Checks if the logged in user has Clone/MultiClone roles assigned
IOTAP_AddOn_RecordClone_HasCloneAccess = function (buttonName,primaryEntityName,selectedEntityName,control)
{
    var button = String(buttonName);
    var cloneAccess = false;
    var isCloneEnabled = false;
    var entityName;
    console.log("IOTAP_AddOn_RecordClone_HasCloneAccess START");
    //in case of subgrid the primary entity is the parent entity, so setting it to the entity in the subgrid
    if ( control == "subgrid" )
        primaryEntityName = selectedEntityName;

    if (primaryEntityName)
        entityName = String(primaryEntityName);
    else
        entityName = String(selectedEntityName);

    console.log("Entity Name " + entityName);

    try {
            var isCloneEnabled = false;

            console.log("User Id " + Xrm.Page.context.getUserId());

            //avoid multiple calls
            if ( !userRoles ) {
                var _fetchXml = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true'>" +
                                    "<entity name='role'>" +
                                    "<attribute name='name' />" +
                                    "<link-entity name='systemuserroles' from='roleid' to='roleid' visible='false' intersect='true'>" +
                                    "<link-entity name='systemuser' from='systemuserid' to='systemuserid' alias='af'>" +
                                    "<filter type='and'>" +
                                    "<condition attribute='systemuserid' operator='eq' value='" + Xrm.Page.context.getUserId() + "' />" +
                                    "</filter>" +
                                    "</link-entity>" +
                                    "</link-entity>" +
                                  "</entity>" +
                                "</fetch>";
                _fetchXml = encodeURI( _fetchXml );                                                       
                userRoles = IOTAP_AddOn_RecordClone_RetrieveMultiple( "roles", "?fetchXml=" + _fetchXml );                
            }

            console.log("User Roles Count " + userRoles.length);

            if (button == "clone")
            {
                for ( i = 0; i < userRoles.length; i++ ) {           
                    if (userRoles[i].name.toLowerCase() == IOTAP_AddOn_RecordClone_cloneRoleId.toLowerCase()) {
                        cloneAccess = true;
                        break;
                    }
                }
            }   
            else
            {
                for ( i = 0; i < userRoles.length; i++ ) {
                    if (userRoles[i].name.toLowerCase() == IOTAP_AddOn_RecordClone_multiCloneRoleId.toLowerCase() ) {
                        cloneAccess = true;
                        break;
                    }
                }
            }

            console.log("Clone Access " + cloneAccess);

            if ( cloneAccess ) {
               
                //avoid multiple calls if already available
                if ( !cloneEnabledEntities ) {
                    cloneEnabledEntities = IOTAP_AddOn_RecordClone_RetrieveMultiple( "iotap_recordclonesettings", "?$select=iotap_entityschemaname,iotap_cloneprompt,iotap_openclonerecord,iotap_clonemultiple&$filter=statecode eq 0" );
                }

                for (var i = 0; i < cloneEnabledEntities.length; i++) {
                    console.log("Clone Enabled Entity " + cloneEnabledEntities[i].iotap_entityschemaname.toLowerCase());
                    if ( cloneEnabledEntities[i].iotap_entityschemaname.toLowerCase() == entityName.toLowerCase() ) {

                        IOTAP_AddOn_RecordClone_ClonePrompt = cloneEnabledEntities[i].iotap_cloneprompt;
                        IOTAP_AddOn_RecordClone_OpenCloneRecord = cloneEnabledEntities[i].iotap_openclonerecord;
                        IOTAP_AddOn_RecordClone_CloneMultiple = cloneEnabledEntities[i].iotap_clonemultiple;

                        isCloneEnabled = true;
                        break;
                    }
                }
                
        }

        console.log("Clone Enabled " + isCloneEnabled);
    }
    catch ( ex ) {
        console.log("ERROR : Clone Button Access [" + ex.message + "]");
    }
    
    return isCloneEnabled;
}

 //Create the HTTP Request object
IOTAP_AddOn_RecordClone_CreateHTTPRequest = function ( action, query, async )
{
    try {

        var httpReq = new XMLHttpRequest();
        httpReq.open( action, IOTAP_AddOn_RecordClone_GetClientUrl() + "/api/data/" + apiVersion + "/" + query, async );
        httpReq.setRequestHeader( "Accept", "application/json" );
        httpReq.setRequestHeader( "Content-Type", "application/json; charset=utf-8" );
        httpReq.setRequestHeader( "OData-MaxVersion", "4.0" );
        httpReq.setRequestHeader( "OData-Version", "4.0" );
    }
    catch(ex)
    {
        throw ex;
    }
    return httpReq;
}

// Retrieve Multiple Records
IOTAP_AddOn_RecordClone_RetrieveMultiple = function ( entity, options )
{
    try
    {
        var coll;
        var query = entity + options;
        var httpReq = IOTAP_AddOn_RecordClone_CreateHTTPRequest( "GET", query, false );
        httpReq.send(null);

        if ( httpReq.status == 200 ) {
            coll = JSON.parse( httpReq.responseText ).value;
        }                
        return coll;
    }
    catch(ex)
    {
        throw ex;
    }
}

IOTAP_AddOn_RecordClone_CreateRecord = function (entityName, entity) {
    try {
        var httpReq = IOTAP_AddOn_RecordClone_CreateHTTPRequest("POST", entityName + "s", false);
        httpReq.send(JSON.stringify(entity));        
    }
    catch (ex) {
        throw ex;
    }
}

IOTAP_AddOn_RecordClone_UpdateRecord = function (entityName, entityId, entity) {
    try {
        var httpReq = IOTAP_AddOn_RecordClone_CreateHTTPRequest("PATCH", entityName + "s(" + entityId + ")", false);
        httpReq.send(JSON.stringify(entity));
    }
    catch (ex) {
        throw ex;
    }
}

IOTAP_AddOn_RecordClone_ConfigSave = function ( context )
{
    try{

        var eventArgs = context.getEventArgs();

        //Disable auto-save 
        if ( eventArgs.getSaveMode() == 70)
            eventArgs.preventDefault();

        //call the webresource save function to capture field values
        var cloneSetting = Xrm.Page.ui.controls.get( "WebResource_recordclonesetting" );
        if (cloneSetting)
            var settingDoc = cloneSetting.getObject().contentWindow;
        if (settingDoc) {
            var retVal = settingDoc.IOTAP_AddOn_RecordClone_ProcessSave();

            if(retVal == false)
                eventArgs.preventDefault();
        }  
    }
    catch (ex) {
        alert("ERROR : IOTAP Record Clone [" + ex.message + "]");
    }
}




