"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.updateModel = updateModel;
const arcgis_rest_portal_1 = require("@esri/arcgis-rest-portal");
const extent_1 = require("../extent");
const util_1 = require("../util");
const getModel_1 = require("./getModel");
const wrappers_1 = require("../rest/portal/wrappers");
/**
 * Update an IModel. Generic function that will be used across all
 * type-specific update functions
 *
 * @export
 * @param {IModel} "model" object (i.e. `{item:{...}, data:{...}}`)
 * @param {IRequestOptions} requestOptions
 * @returns {Promise<IModel>}
 */
function updateModel(model, requestOptions) {
    // const clone = cloneObject(model);
    const item = (0, util_1.cloneObject)(model.item);
    item.data = (0, util_1.cloneObject)(model.data);
    // Update extent from bbox to string
    // TODO: remove below logic once rest.js is fixed.
    if (item.extent && typeof item.extent !== "string") {
        // THIS IS A HACK TO WORK AROUND REST.JS BUG
        // and normally should never be done.
        item.extent = (0, extent_1.bboxToString)(item.extent);
    }
    // If we have a field we are trying to clear (by making it an empty string like description / snippet)
    // We need to send clearEmptyFields: true to the updateItem call
    if (shouldClearEmptyFields(item)) {
        requestOptions.params = Object.assign(Object.assign({}, requestOptions.params), { clearEmptyFields: true });
    }
    const opts = Object.assign({ item }, requestOptions);
    return (0, wrappers_1.updateItem)(opts).then(() => {
        // To ensure we have the exact modified timestamp, we need to
        // get the item again
        // Also, we can't just call getModel because we need to be able
        // to properly handle other types like PDFs that don't have JSON data
        return item.data
            ? (0, getModel_1.getModel)(item.id, requestOptions)
            : (0, arcgis_rest_portal_1.getItem)(item.id, requestOptions).then((i) => ({ item: i }));
        // // update the modified prop
        // // this won't be exact, but it will be very close
        // clone.item.modified = new Date().getTime();
        // return clone;
    });
}
/**
 * Given an Item, determine if there are any fields to be cleared
 *
 * @param {IItem} item
 * @return {*} boolean
 */
function shouldClearEmptyFields(item) {
    return ["description", "snippet", "tags", "categories", "licenseInfo"].some((field) => { var _a; return item[field] === "" || ((_a = item[field]) === null || _a === void 0 ? void 0 : _a.length) === 0; });
}
//# sourceMappingURL=updateModel.js.map