"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var BringgDashboardSDK_1 = require("../../BringgDashboardSDK");
var BaseService_1 = __importDefault(require("../../Core/BaseService"));
var BringgException_1 = require("../../Core/BringgException");
var ExceptionReason_1 = require("../../Core/ExceptionReason");
var Enums_1 = require("../../Core/Http/Enums");
var URLEndpoint_1 = __importDefault(require("../../Core/Http/URLEndpoint"));
var Polly_1 = __importDefault(require("../../Core/Polly"));
var RouteGenerator_1 = require("../../Core/RouteGenerator");
var Route_1 = require("../../Services/Route");
var ServiceRequest_1 = require("../../Services/ServiceRequest");
var upload_consts_1 = require("./upload.consts");
var UploadService = /** @class */ (function () {
    function UploadService(session) {
        this.service = new BaseService_1.default(session, 'uploads');
    }
    /**
     * Fetches the metadata for a given upload by it's id.
     * The response will also contain signed urls for downloading the upload content or uploading to it.
     * The options contain optional parameters for signing these urls.
     * @param id The upload id to fetch.
     * @param options Search options.
     * @returns The found upload, or null if not found.
     */
    UploadService.prototype.get = function (id, options) {
        return __awaiter(this, void 0, void 0, function () {
            var error_1;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 2, , 3]);
                        return [4 /*yield*/, this.service.routeGenerator
                                .get(upload_consts_1.Routes.GET)
                                .withRouteParams({ id: id })
                                .withQueryString(options || {})
                                .invoke()];
                    case 1: return [2 /*return*/, _a.sent()];
                    case 2:
                        error_1 = _a.sent();
                        if (this.isNotFoundError(error_1)) {
                            return [2 /*return*/, null];
                        }
                        throw (0, RouteGenerator_1.createServiceError)('Failed to get upload.');
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Redirects to download the content of the upload object which matches the given related record.
     * @param id The upload id to fetch.
     * @returns The upload's file content buffer, or null if not found.
     */
    UploadService.prototype.getContent = function (id) {
        return __awaiter(this, void 0, void 0, function () {
            var error_2;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 2, , 3]);
                        return [4 /*yield*/, this.service.routeGenerator
                                .get(upload_consts_1.Routes.GET_CONTENT)
                                .withRouteParams({ id: id })
                                // This is a file, so return the raw ArrayBuffer instead of a parsed String.
                                .withResponseType('arraybuffer')
                                .invoke()];
                    case 1: return [2 /*return*/, _a.sent()];
                    case 2:
                        error_2 = _a.sent();
                        if (this.isNotFoundError(error_2)) {
                            return [2 /*return*/, null];
                        }
                        throw (0, RouteGenerator_1.createServiceError)('Failed to download the file content.');
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Redirects to download the content of the upload object as an image, allowing to provide image processing options to get a specific image version.
     * The expiration option determines the expiration in seconds of the redirected download url, as well as how long the url will be cached on the server.
     * While cached, for the same request parameters the same redirect url will be returned, allowing better caching for the content.
     * @param id The id of the download image to fetch.
     * @param options Optionally, provide the variation of the image (for example 'thumbnail') and the expiration of the download link.
     * @returns The image content, or null if not found.
     */
    UploadService.prototype.getImage = function (id, options) {
        return __awaiter(this, void 0, void 0, function () {
            var error_3;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 2, , 3]);
                        return [4 /*yield*/, this.service.routeGenerator
                                .get(upload_consts_1.Routes.GET_IMAGE)
                                .withRouteParams({ id: id })
                                .withQueryString(options)
                                .withResponseType('arraybuffer')
                                .invoke()];
                    case 1: return [2 /*return*/, _a.sent()];
                    case 2:
                        error_3 = _a.sent();
                        if (this.isNotFoundError(error_3)) {
                            return [2 /*return*/, null];
                        }
                        throw (0, RouteGenerator_1.createServiceError)('Failed to download upload image.');
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Fetches the metadata for a given upload by the record it relates to.
     * The response will also contain signed urls for downloading the upload content or uploading to it.
     * The options contain optional parameters for signing these urls.
     * @param recordId The id of the related record.
     * @param recordType The type of the related record.
     * @param attachmentType Optional filter by the attachment type of the upload (in case the record has multiple uploads).
     * @param options Search options.
     * @returns The found upload, or null if not found.
     */
    UploadService.prototype.getByRecord = function (recordId, recordType, attachmentType, options) {
        return __awaiter(this, void 0, void 0, function () {
            var queryOptions, error_4;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        queryOptions = options || {};
                        if (attachmentType) {
                            queryOptions = __assign({ attachment_type: attachmentType }, queryOptions);
                        }
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, this.service.routeGenerator
                                .get(upload_consts_1.Routes.GET_BY_RECORD)
                                .withRouteParams({ record_id: recordId, record_type: recordType })
                                .withQueryString(queryOptions)
                                .invoke()];
                    case 2: return [2 /*return*/, _a.sent()];
                    case 3:
                        error_4 = _a.sent();
                        if (this.isNotFoundError(error_4)) {
                            return [2 /*return*/, null];
                        }
                        throw (0, RouteGenerator_1.createServiceError)('Failed to get upload.');
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Downloads the content of the upload object which matches the given related record.
     * @param recordId The id of the related record.
     * @param recordType The type of the related record.
     * @param attachmentType Optional filter by the attachment type of the upload (in case the record has multiple uploads).
     * @returns The upload's file content buffer, or null if not found.
     */
    UploadService.prototype.getContentByRecord = function (recordId, recordType, attachmentType) {
        return __awaiter(this, void 0, void 0, function () {
            var queryOptions, error_5;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        queryOptions = {};
                        if (attachmentType) {
                            queryOptions.attachment_type = attachmentType;
                        }
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, this.service.routeGenerator
                                .get(upload_consts_1.Routes.GET_CONTENT_BY_RECORD)
                                .withRouteParams({ record_id: recordId, record_type: recordType })
                                .withQueryString(queryOptions)
                                .withResponseType('arraybuffer')
                                .invoke()];
                    case 2: return [2 /*return*/, _a.sent()];
                    case 3:
                        error_5 = _a.sent();
                        if (this.isNotFoundError(error_5)) {
                            return [2 /*return*/, null];
                        }
                        throw (0, RouteGenerator_1.createServiceError)('Failed to download the file content.');
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Allows fetching multiple uploads metadata on the same request.
     * Returns an empty array if no results found.
     * Each search parameter must include the merchant id, and either the upload's id or record id and type.
     * @param params The search parameters.
     * @param options Optional signature options for the upload and download urls returned on the results.
     * @returns An array of the metadata of the found uploads, with signed urls for uploading and downloading files for it.
     */
    UploadService.prototype.getBatch = function (params, options) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.service.routeGenerator
                            .post(upload_consts_1.Routes.GET_BATCH)
                            .withPayload({ batch: params, signature: options })
                            .setException('Failed to get uploads.')
                            .invoke()];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    /**
     * Deletes the given upload.
     * By default, only deletes the upload's metadata which references the file. To also delete the file content, pass the 'content' argument.
     * @param id The upload's id.
     * @param content When true, will also delete the upload content from the storage.
     * @returns true if the upload was deleted; false if it was not found.
     */
    UploadService.prototype.delete = function (id, content) {
        return __awaiter(this, void 0, void 0, function () {
            var queryParams, error_6;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        queryParams = content ? { content: content } : {};
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, this.service.routeGenerator
                                .delete(upload_consts_1.Routes.DELETE)
                                .withRouteParams({ id: id })
                                .withQueryString(queryParams)
                                .invoke()];
                    case 2:
                        _a.sent();
                        return [2 /*return*/, true];
                    case 3:
                        error_6 = _a.sent();
                        if (this.isNotFoundError(error_6)) {
                            return [2 /*return*/, false];
                        }
                        throw (0, RouteGenerator_1.createServiceError)('Failed to delete upload.');
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Creates an upload, and optionally uploads the given file content to the created upload's destination.
     * If a file is provided and uploaded, a second request to update the upload's 'stored_at' time will be made.
     * @param request The metadata to create the upload with.
     * @param options Optional url signature and file upload options.
     * @param file Optional file content to save for the upload.
     * @returns The id of the created upload.
     */
    UploadService.prototype.create = function (request, options, file) {
        return __awaiter(this, void 0, void 0, function () {
            var payload, response;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        options = options || {};
                        payload = __assign(__assign({}, request), this.extractSignatureOptions(options));
                        return [4 /*yield*/, this.service.routeGenerator
                                .post(upload_consts_1.Routes.CREATE)
                                .withPayload(payload)
                                .setException('Failed to create upload.')
                                .invoke()];
                    case 1:
                        response = _a.sent();
                        if (!file) return [3 /*break*/, 4];
                        return [4 /*yield*/, this.uploadFile(response.upload_url, options, file)];
                    case 2:
                        _a.sent();
                        return [4 /*yield*/, this.update(response.id, { stored_at: new Date() })];
                    case 3:
                        _a.sent();
                        _a.label = 4;
                    case 4: return [2 /*return*/, response.id];
                }
            });
        });
    };
    UploadService.prototype.extractSignatureOptions = function (options) {
        if (!options) {
            return {};
        }
        var res = {};
        var signatureProps = ['content_type', 'content_md5', 'expiration'];
        signatureProps.forEach(function (prop) {
            if (options[prop]) {
                res[prop] = options[prop];
            }
        });
        return res;
    };
    /**
     * Updates the given upload.
     * @param id The id of the upload to update.
     * @param request The fields to update.
     */
    UploadService.prototype.update = function (id, request) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.service.routeGenerator
                            .put(upload_consts_1.Routes.UPDATE)
                            .withRouteParams({ id: id })
                            .withPayload(request)
                            .setException('Failed to update upload.')
                            .invoke()];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    UploadService.prototype.uploadFile = function (url, options, file) {
        return __awaiter(this, void 0, void 0, function () {
            var res;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, new Polly_1.default()
                            .handle(function (error) {
                            var _a;
                            if (((_a = error.response) === null || _a === void 0 ? void 0 : _a.status) && upload_consts_1.RETRYABLE_UPLOAD_ERRORS.includes(error.response.status)) {
                                return true;
                            }
                            return false;
                        })
                            .waitAndRetry(options.file_upload_retries || 10)
                            .executeForPromise(function () {
                            var parsedUrl = new URL(url);
                            return new ServiceRequest_1.AnonymousServiceRequest((0, BringgDashboardSDK_1.getConfigurationProvider)().getClientId(), _this.getUploadHeaders(options))
                                .invoke(URLEndpoint_1.default.parse(url), new Route_1.Route(parsedUrl.pathname, 2 /* HttpMethod.PUT */), null, parsedUrl.searchParams, file)
                                .handle(function (res) {
                                if (res instanceof Error) {
                                    throw res;
                                }
                                if (!res.status || res.status < 200 || res.status > 299) {
                                    var error = new Error("Failed uploading file with status: ".concat(res.status, " - ").concat(res.statusText));
                                    // This is similar to the structure of an actual axios error.
                                    error.response = res;
                                    throw error;
                                }
                                return res;
                            });
                        })];
                    case 1:
                        res = _a.sent();
                        // The retry class returns the error, not throws it.
                        if (res instanceof Error) {
                            throw res;
                        }
                        return [2 /*return*/];
                }
            });
        });
    };
    UploadService.prototype.getUploadHeaders = function (options) {
        var headers = {
            'Content-Type': options.content_type || 'application/octet-stream'
        };
        if (options.content_md5) {
            headers['Content-MD5'] = options.content_md5;
        }
        return headers;
    };
    UploadService.prototype.isNotFoundError = function (error) {
        // Raw not found axios response
        if (error.status === Enums_1.HttpStatusCode.NOT_FOUND) {
            return true;
        }
        // Wrapped request not found error. Not actually thrown on the current flows, but it could be.
        if (error instanceof BringgException_1.BringgException && error.reason === ExceptionReason_1.ExceptionReason.HTTP_NOT_FOUND) {
            return true;
        }
        return false;
    };
    return UploadService;
}());
exports.default = UploadService;
//# sourceMappingURL=upload-service.js.map