<script type="text/javascript">
/**
 * Check if the URL has the clearSelected param
 * @return {Boolean}
 */
function isClearSelectedFlagged(flagName = 'clearSelected') {
    var params = new URLSearchParams(window.location.search);
    return params.get(flagName) ? true : false;
}

/**
 * Reset the clearSelected param in the URL
 */
function resetClearSelectedFlag(flagName = 'clearSelected') {
    // remove the clear param from the URL without reloading the page or adding a history entry
    var params = new URLSearchParams(window.location.search);
    params.delete(flagName);
    var newQuery = params.toString();
    var newUrl = window.location.pathname + (newQuery ? '?' + newQuery : '') + window.location.hash;
    history.replaceState(null, '', newUrl);
}

/**
 * Get the column index of the checkbox column in a DataTable.
 *
 * @param  DataTable dataTable
 * @return int|null
 */
function getDtCheckboxColumn(dataTable) {
    var columnNumber = null;
    var count = dataTable.DataTable().columns().length;
    for (var i = 0; i < count; i++) {
        // find column that is checkboxes
        if (dataTable.DataTable().column(i).checkboxes) {
            columnNumber = i;
            break;
        }
    }

    return columnNumber;
}

/**
 * Get the number of selected checkboxes in a given column of a DataTable.
 *
 * @param  DataTable dataTable
 * @param  int|null  columnNumber
 * @return int
 */
function getDtNumberChecked(dataTable, columnNumber) {
    if (columnNumber !== null) {
        return dataTable.DataTable().column(columnNumber).checkboxes.selected().length;
    }
    return 0;
}

/**
 * Clear all selected checkboxes in a given column of a DataTable.
 *
 * @param Datatable dataTable
 * @param int|null  columnNumber
 */
function dtClearSelected(dataTable, columnNumber) {
    if (columnNumber !== null) {
        dataTable.DataTable().column(columnNumber).checkboxes.deselectAll();
    }
}

/**
 * Handle clearing selected checkboxes in a DataTable if the URL has the clearSelected param.
 *
 * @param  Datatable dataTable
 * @param  int|null  columnNumber
 * @param  {String}  flagName
 */
function handleDtClearSelected(dataTable, columnNumber, flagName = 'clearSelected') {
    if (isClearSelectedFlagged(flagName)) {
        if (columnNumber === null) {
            columnNumber = getDtCheckboxColumn(dataTable);
        }
        // if the URL has the clearSelected param, clear any selected checkboxes
        dtClearSelected(dataTable, columnNumber);
        resetClearSelectedFlag(flagName);
    }
}
</script>
