/* Minification failed. Returning unminified contents.
(29,16-17): run-time error JS1195: Expected expression: >
(32,19-22): run-time error JS1004: Expected ';': new
(32,40-41): run-time error JS1195: Expected expression: >
(32,66-67): run-time error JS1004: Expected ';': )
(35,5-6): run-time error JS1002: Syntax error: }
(38,38-39): run-time error JS1004: Expected ';': {
 */
document.addEventListener("at-request-failed", function (event) {
    console.log('Adobe Target - at-request-failed');
});
document.addEventListener("at-request-succeeded", function (event) {
    console.log('Adobe Target - at-request-succeeded');
});
document.addEventListener("at-content-rendering-failed", function (event) {
    console.log('Adobe Target - at-content-rendering-failed');
});
document.addEventListener("at-library-loaded", function (event) {
    console.log('Adobe Target - at-library-loaded');
});
document.addEventListener("at-request-start", function (event) {
    console.log('Adobe Target - at-request-start');
});
document.addEventListener("at-content-rendering-start", function (event) {
    console.log('Adobe Target - at-content-rendering-start');
});
document.addEventListener("at-content-rendering-no-offers", function (event) {
    console.log('Adobe Target - at-content-rendering-no-offers');
});
document.addEventListener("at-content-rendering-redirect", function (event) {
    console.log('Adobe Target - at-content-rendering-redirect');
});

// Target processing - we listen to hear a successful rendering of target items on the page - then we look to see if amendments have been made
document.addEventListener("at-content-rendering-succeeded", function (event) {
    console.log('Adobe Target - at-content-rendering-succeeded');
    (async () => {
        console.log("waiting for digitaldata variable");
        while (!window.hasOwnProperty("digitalData")) // define the condition as you like
            await new Promise(resolve => setTimeout(resolve, 100));
        console.log("digitaldata variable is defined");
        ProcessTargetUpdates(event);
    })();
});

function ProcessTargetUpdates(event) {
    //Target processing - this is for any html that has been changed through the official channel of uploading sitecore snippets
    //Once Target has finished processing - this is the delete function - if the ID that is in the digitalData object doesn't exist
    //anymore then remove it from the array
    console.log("Processing of sitecore uploaded changes to Target started");

    if (typeof digitalData !== 'undefined' && digitalData != null && digitalData.page_assets != null) {
        const assetsToDelete = [];
        console.log("processing deletions");

        //Because of the way the content developers switch out content - some html is left on the page even though the content has been replaced
        //We need to check the ID of content immediately prior to where standard=false as we know the ID that immediately precedes this needs removing
        //== The following section removes not only that replaced item - but if it is a group - the 'RemoveFromDatalayer' will remove subsequent items ==//
        let allElements = [];
        $j('*[data-tag-standard="false"],*[data-tag-standard="true"]').each(function () {
            var idAttr = $j(this).attr('data-tag-id');
            var stdAttr = $j(this).attr('data-tag-standard');
            var extractElement = {};
            extractElement.data_layer_key = idAttr;
            extractElement.data_layer_standard = stdAttr;
            allElements.push(extractElement);
        });
        var previousAsset = {};
        allElements.forEach(function (asset) {
            if (asset.data_layer_standard == "false") {
                if (previousAsset.data_layer_standard == "true") {
                    var idToDelete = {};
                    idToDelete.asset_id = previousAsset.data_layer_key;
                    assetsToDelete.push(idToDelete);
                }
            }
            previousAsset = asset;
        });

        assetsToDelete.forEach(function (asset) {
            console.log("deletion found - " + asset.asset_id);
            RemoveFromDatalayer({ element: asset.asset_id, change_type: "remove" });
        });
        //== this is the end of the removal==//
    }
    else {
        console.log("digitalData or digitalData.page_assets is null - therefore cannot be updated yet");
    }

    //Whether it is an add or an amend, the data-tag_standard field will be set to false
    //If the data-tag-id is not within the digitalData.page_assets then it's an add
    //If there is a match then it's an update - all the values on the element prefixed data-tag should be used to update the datalayer
    console.log("processing add and updates");
    $j('*[data-tag-standard="false"]').each(function () {
        console.log("standard-false found");
        var idAttr = $j(this).attr('data-tag-id');
        if (typeof idAttr !== 'undefined' && idAttr !== false) {
            console.log("Standard - false flag found, attempting to process ID - " + idAttr);
            //Does the ID in the amended html have a corresponding value in the digitalData page_asset
            var matchFound = false;
            var changeType = "add";
            if (digitalData != null && digitalData.page_assets != null) {
                digitalData.page_assets.forEach(function (asset) {
                    if (typeof asset.asset_id !== 'undefined' && asset.asset_id !== false) {
                        if (asset.asset_id.toLowerCase() == idAttr.toLowerCase()) {
                            matchFound = true;
                        }
                    }
                });
            }
            //Create a new object in order to use the common processing and update the digitalData
            var assetElement = new Object();
            assetElement.element = idAttr;
            const dataValues = [];
            //Get the list of attributes from the html
            $j.each(this.attributes, function (i, attrib) {
                var name = attrib.name;
                var value = attrib.value;
                //We want to get all the attribues that are prefixed with data-tag and use them to update info
                if (name.includes("data-tag")) {
                    var dataValue = {};
                    var newKey = name.replace('data-tag-id', 'data-tag-asset_id');
                    newKey = newKey.replace('data-tag-', '');
                    dataValue.data_layer_key = newKey;
                    dataValue.data_layer_value = value;
                    dataValues.push(dataValue);
                }
            });
            assetElement.values = dataValues;
            if (matchFound == true) {
                changeType = "update"
                assetElement.change_type = changeType;
                UpdateDatalayer(assetElement);
            }
            else {
                assetElement.change_type = changeType;
                AddToDatalayer(assetElement);
            }
        }
        else {
            console.log("There is no data-tag-id field to match against.");
        }
    });
    console.log("Processing of sitecore uploaded changes to Target ended");

    console.log("Processing of direct changes to Target started");
    //Direct target updates are coupled with sets of changes added to the window
    if (window.changes != null && window.changes.length > 0) {
        console.log("Target changes found to process - " + window.changes.length);
        window.changes.forEach(function (entry) {
            if (entry.change_type != null) {
                switch (entry.change_type) {
                    case "remove":
                        RemoveFromDatalayer(entry);
                        break;
                    case "add":
                        AddToDatalayer(entry);
                        break;
                    case "update":
                        UpdateDatalayer(entry);
                        break;
                    default:
                        console.log("the change_type was not valid, it need to be add, remove, or update");
                }
            }
            else {
                console.log("the entry was missing a change_type");
            }
            console.log(entry);
        });
    }
    else {
        console.log("no Target changes to process");
    }
    console.log("Processing of direct changes to Target ended");
};

function RemoveFromDatalayer(entry) {
    if (entry.element != null) {
        var matchingAssetFound = false;
        const newAssets = [];
        var processAsset = true;
        var ignoreAssetCount = 0;
        digitalData.page_assets.forEach(function (asset) {
            if (ignoreAssetCount == 0) { processAsset = true; }
            if (processAsset == true) {
                if (asset.asset_id.toLowerCase() == entry.element.toLowerCase()) {
                    //If delete is set at a group level we need to remove the group and child items
                    if (typeof asset.asset_category !== 'undefined' && asset.asset_category !== false) {
                        if (asset.asset_category.toLowerCase() == "group") {
                            //The group item will tell us how many items are within in
                            if (asset.number_in_group != null) { ignoreAssetCount = asset.number_in_group; }
                            if (asset.number_of_tabs != null) { ignoreAssetCount = asset.number_in_group; }
                            processAsset = false;
                            console.log("Remove - Matching group asset found");
                        }
                        else {
                            console.log("Remove - Matching single asset found");
                        }
                    }
                    else {
                        console.log("Remove - Matching single asset found");
                    }
                    matchingAssetFound = true;
                }
                else {
                    newAssets.push(asset);
                }
            }
            else {
                ignoreAssetCount--;
                console.log("Remove - Group asset item");
            }
        });
        if (matchingAssetFound == false) {
            console.log("No matching datalayer item found to delete.");
        }
        else {
            digitalData.page_assets = newAssets;
        }
    }
    else {
        console.log("The javascript is not valid - there is no entry id to delete against.");
    }
};

function AddToDatalayer(entry) {
    var newAsset = {};
    entry.values.forEach(function (updateValue) {
        console.log("add data layer key - " + updateValue.data_layer_key);
        console.log("add data layer value - " + updateValue.data_layer_value);
        newAsset[updateValue.data_layer_key] = updateValue.data_layer_value;
    });
    var addEntry = true;
    digitalData.page_assets.forEach(function (asset) {
        if (newAsset.asset_id.toLowerCase() == asset.asset_id.toLowerCase()) {
            addEntry = false;
        }
    });
    if (addEntry == true) {
        digitalData.page_assets.push(newAsset);
        console.log("Add - new asset added.");
    }
    else {
        console.log("Add - duplicate found - asset not added.");
    }
};

function UpdateDatalayer(entry) {
    var matchingAssetFound = false;
    const newAssets = [];
    digitalData.page_assets.forEach(function (asset) {
        if (asset.asset_id.toLowerCase() == entry.element.toLowerCase()) {
            var newAsset = asset;
            console.log("Update - Matching asset found - " + asset.asset_id);
            matchingAssetFound = true;
            entry.values.forEach(function (updateValue) {
                console.log("update data layer key - " + updateValue.data_layer_key);
                console.log("update data layer value - " + updateValue.data_layer_value);
                //Asset is our collection of asset data within digitalData object
                //We have the new key and value from the entry, so need to find the matching key within asset and update it with the new value
                newAsset[updateValue.data_layer_key] = updateValue.data_layer_value;
            });
            newAssets.push(newAsset);
        }
        else {
            newAssets.push(asset);
        }
    });
    if (matchingAssetFound == false) {
        console.log("No matching datalayer item found to update.");
    }
    else {
        digitalData.page_assets = newAssets;
    }
};;
