"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.updateVersion = updateVersion;
const get_prop_1 = require("../objects/get-prop");
const merge_objects_1 = require("../objects/merge-objects");
const object_to_json_blob_1 = require("../resources/object-to-json-blob");
const getPrefix_1 = require("./_internal/getPrefix");
const getVersionData_1 = require("./_internal/getVersionData");
const constants_1 = require("./_internal/constants");
const getIncludeListFromItemType_1 = require("./_internal/getIncludeListFromItemType");
const arcgis_rest_portal_1 = require("@esri/arcgis-rest-portal");
const utils_1 = require("./utils");
/**
 * Custom error to be thrown when attempting to save a stale version
 * @class StaleVersionError
 * @extends {Error}
 */
class StaleVersionError extends Error {
    constructor(id, updated) {
        super(`Version ${id} is stale. Use force to overwrite.`);
        this.updated = updated;
        this.name = "StaleVersionError";
    }
}
/**
 * Updates the specified version with with the state of the supplied model
 * throws an exception if the version is stale and force is not true
 * @param model
 * @param version
 * @param requestOptions
 * @param force
 * @returns
 */
async function updateVersion(model, version, requestOptions, force) {
    // we expect the model to contain the changes that we want to apply to the version
    // but we also need the versionResource so we can preserve the created and creator props
    if (!force) {
        const isStaleResponse = await (0, utils_1.checkForStaleVersion)(model.item.id, version, requestOptions);
        if (isStaleResponse.isStale) {
            throw new StaleVersionError(version.id, isStaleResponse.updated);
        }
    }
    const includeList = (0, getIncludeListFromItemType_1.getIncludeListFromItemType)(model);
    version.data = (0, getVersionData_1.getVersionData)(model, includeList);
    const prefix = (0, getPrefix_1.getPrefix)(version.id);
    version.updated = Date.now();
    const versionBlob = (0, object_to_json_blob_1.objectToJsonBlob)(version);
    const properties = (0, merge_objects_1.mergeObjects)(version, {}, constants_1.VERSION_RESOURCE_PROPERTIES);
    await (0, arcgis_rest_portal_1.updateItemResource)(Object.assign(Object.assign({}, requestOptions), { id: (0, get_prop_1.getProp)(model, "item.id"), name: constants_1.VERSION_RESOURCE_NAME, owner: (0, get_prop_1.getProp)(model, "item.owner"), params: { properties }, prefix, resource: versionBlob }));
    return version;
}
//# sourceMappingURL=updateVersion.js.map