"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.upsertResource = upsertResource;
const arcgis_rest_portal_1 = require("@esri/arcgis-rest-portal");
const HubError_1 = require("../HubError");
const get_portal_api_url_1 = require("../urls/get-portal-api-url");
const doesResourceExist_1 = require("./doesResourceExist");
const object_to_json_blob_1 = require("./object-to-json-blob");
const string_to_blob_1 = require("./string-to-blob");
/**
 * Given an item, and owner, Search for if the resource exists
 * and if does, update it, otherwise add it. Returns a url for the item.
 *
 * @export
 * @param {string} id
 * @param {string} owner
 * @param {*} resource
 * @param {string} name
 * @param {IUserRequestOptions} ro
 * @param {string} [prefix=""]
 * @return {*}  {Promise<string>}
 */
async function upsertResource(id, owner, resource, name, ro, prefix = "") {
    try {
        const extension = name.split(".").pop();
        // Search against the item resources to see if the resource exists
        const doesResExist = await (0, doesResourceExist_1.doesResourceExist)(id, name, ro);
        // if the resource exists, update it, otherwise add it
        const resourceFunc = doesResExist ? arcgis_rest_portal_1.updateItemResource : arcgis_rest_portal_1.addItemResource;
        // JSON and text resources have....odd things happen
        // to them when they are added as resources and NOT
        // converted to blobs. Thus we convert them to blobs
        let resourceToUpload = resource;
        if (extension === "json") {
            resourceToUpload = (0, object_to_json_blob_1.objectToJsonBlob)(resource);
        }
        if (extension === "txt") {
            resourceToUpload = (0, string_to_blob_1.stringToBlob)(resource);
        }
        // Add item resource
        const response = await resourceFunc(Object.assign({ id,
            owner, resource: resourceToUpload, name,
            prefix }, ro));
        // if err throw
        if (!response.success) {
            throw new HubError_1.default("Add Item Resource", `Error adding resource ${name} to item ${id}.`);
        }
        // return url
        const portalRestUrl = (0, get_portal_api_url_1.getPortalApiUrl)(ro.portal);
        const _prefix = prefix ? `${prefix}/` : "";
        return `${portalRestUrl}/content/items/${id}/resources/${_prefix}${name}`;
    }
    catch (err) {
        if (err instanceof Error) {
            throw new HubError_1.default("Add Item Resource", err.message, err);
        }
        else {
            throw new HubError_1.default("Add Item Resource", `Error adding resource ${name} to item ${id}.`);
        }
    }
}
//# sourceMappingURL=upsertResource.js.map