"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 });
exports.RunsService = exports.Routes = void 0;
var BringgException_1 = require("../../Core/BringgException");
var CrudService_1 = __importDefault(require("../../Core/CrudService"));
var Route_1 = require("../../Services/Route");
var array_utils_1 = require("../../utils/array-utils");
var runs_consts_1 = require("../runs.consts");
exports.Routes = {
    GET_RUNS: new Route_1.Route('/runs', 0 /* HttpMethod.GET */),
    GET_RUN_DATA: new Route_1.Route('/data-query-service/query', 1 /* HttpMethod.POST */),
    GET_RUN: new Route_1.Route('/runs/{:id}', 0 /* HttpMethod.GET */),
    UPDATE_RUN: new Route_1.Route('/runs/{:id}', 3 /* HttpMethod.PATCH */),
    GET_RUN_HISTORY: new Route_1.Route('/runs/{:id}/history', 0 /* HttpMethod.GET */),
    GET_RUN_LOCATIONS: new Route_1.Route('/runs/{:id}/locations', 0 /* HttpMethod.GET */),
    GET_RUN_CASHOUT: new Route_1.Route('/runs/{:id}/cashout', 0 /* HttpMethod.GET */),
    ASSIGN_DRIVER: new Route_1.Route('/runs/{:id}/assign', 2 /* HttpMethod.PUT */),
    UNASSIGN_DRIVER: new Route_1.Route('/runs/{:id}/unassign', 2 /* HttpMethod.PUT */),
    BULK_CLOSE: new Route_1.Route('/runs/bulk_close', 1 /* HttpMethod.POST */),
    MARK_DONE_PLANNING: new Route_1.Route('/runs/mark_done_planning', 1 /* HttpMethod.POST */),
    GET_ACTUAL_BREAKS: new Route_1.Route('/runs/actual_breaks', 0 /* HttpMethod.GET */),
    ASSIGN_VEHICLES: new Route_1.Route('/runs/{:id}/vehicles_assignment', 3 /* HttpMethod.PATCH */),
    UNASSIGN_VEHICLES: new Route_1.Route('/runs/{:id}/vehicles_assignment', 4 /* HttpMethod.DELETE */)
};
var RunsService = /** @class */ (function () {
    function RunsService(session) {
        this.service = new CrudService_1.default(session, 'runs');
    }
    RunsService.prototype.getAll = function (options, _a) {
        var _b = _a === void 0 ? {} : _a, signal = _b.signal;
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0: return [4 /*yield*/, this.service.handleAuthorizedRequest({
                            route: exports.Routes.GET_RUNS,
                            extractor: runs_consts_1.defaultExtractor,
                            exceptionProducer: BringgException_1.BringgException.serviceException('Failed to get Runs'),
                            queryString: options,
                            signal: signal
                        })];
                    case 1: return [2 /*return*/, _c.sent()];
                }
            });
        });
    };
    RunsService.prototype.loadRunsData = function (payload, _a) {
        var _b = _a === void 0 ? {} : _a, signal = _b.signal;
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0: return [4 /*yield*/, this.service.handleAuthorizedRequest({
                            route: exports.Routes.GET_RUN_DATA,
                            extractor: runs_consts_1.defaultExtractor,
                            exceptionProducer: BringgException_1.BringgException.serviceException('Failed to get routes data'),
                            payload: payload,
                            signal: signal
                        })];
                    case 1: return [2 /*return*/, _c.sent()];
                }
            });
        });
    };
    RunsService.prototype.loadAll = function (options, commonOptions) {
        if (commonOptions === void 0) { commonOptions = {}; }
        return __awaiter(this, void 0, void 0, function () {
            var runs;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!(!options.ids || options.ids.length <= runs_consts_1.GetAllChunkSize)) return [3 /*break*/, 1];
                        return [2 /*return*/, this.loadPage(__assign({ page: 1 }, options), commonOptions)];
                    case 1:
                        runs = [];
                        return [4 /*yield*/, this.loadPageChunked(__assign({ page: 1 }, options), array_utils_1.arrayUtils.splitToChunks(options.ids, runs_consts_1.GetAllChunkSize), runs, 0, commonOptions)];
                    case 2:
                        _a.sent();
                        return [2 /*return*/, runs];
                }
            });
        });
    };
    RunsService.prototype.loadPageChunked = function (options, idsChunks, allRuns, i, commonOptions) {
        if (i === void 0) { i = 0; }
        if (commonOptions === void 0) { commonOptions = {}; }
        return __awaiter(this, void 0, void 0, function () {
            var runsChunk;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!idsChunks[i]) {
                            return [2 /*return*/, allRuns];
                        }
                        return [4 /*yield*/, this.loadPage(__assign(__assign({}, options), { ids: idsChunks[i] }), commonOptions)];
                    case 1:
                        runsChunk = _a.sent();
                        Array.prototype.push.apply(allRuns, runsChunk);
                        return [2 /*return*/, this.loadPageChunked(options, idsChunks, allRuns, i + 1, commonOptions)];
                }
            });
        });
    };
    RunsService.prototype.loadPage = function (options, commonOptions) {
        if (commonOptions === void 0) { commonOptions = {}; }
        return __awaiter(this, void 0, void 0, function () {
            var response, runs, _a, _b;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0: return [4 /*yield*/, this.getAll(options, commonOptions)];
                    case 1:
                        response = _c.sent();
                        if (!response.success) {
                            throw new Error("Error fetching runs, error code: ".concat(response.rc));
                        }
                        runs = response.runs;
                        if (!response.next_page) return [3 /*break*/, 3];
                        _b = (_a = runs).concat;
                        return [4 /*yield*/, this.loadPage(__assign(__assign({}, options), { page: options.page + 1 }), commonOptions)];
                    case 2:
                        runs = _b.apply(_a, [_c.sent()]);
                        _c.label = 3;
                    case 3: return [2 /*return*/, runs];
                }
            });
        });
    };
    RunsService.prototype.load = function (id, _a) {
        var _b = _a === void 0 ? {} : _a, signal = _b.signal;
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0: return [4 /*yield*/, this.service.handleAuthorizedRequest({
                            route: exports.Routes.GET_RUN,
                            extractor: runs_consts_1.runExtractor,
                            exceptionProducer: BringgException_1.BringgException.serviceException('Failed to get Run'),
                            routeParams: { id: id },
                            signal: signal
                        })];
                    case 1: return [2 /*return*/, _c.sent()];
                }
            });
        });
    };
    RunsService.prototype.update = function (id, options, _a) {
        var _b = _a === void 0 ? {} : _a, signal = _b.signal;
        return __awaiter(this, void 0, void 0, function () {
            var response;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0: return [4 /*yield*/, this.service.handleAuthorizedRequest({
                            route: exports.Routes.UPDATE_RUN,
                            extractor: runs_consts_1.defaultExtractor,
                            exceptionProducer: BringgException_1.BringgException.serviceException('Failed to update Run'),
                            payload: options,
                            routeParams: { id: id },
                            signal: signal
                        })];
                    case 1:
                        response = _c.sent();
                        return [2 /*return*/, response.run];
                }
            });
        });
    };
    RunsService.prototype.getHistory = function (id, _a) {
        var _b = _a === void 0 ? {} : _a, signal = _b.signal;
        return __awaiter(this, void 0, void 0, function () {
            var runHistory;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0: return [4 /*yield*/, this.service.handleAuthorizedRequest({
                            route: exports.Routes.GET_RUN_HISTORY,
                            extractor: runs_consts_1.runsHistoryExtractor,
                            exceptionProducer: BringgException_1.BringgException.serviceException('Failed to get run history'),
                            routeParams: { id: id },
                            signal: signal
                        })];
                    case 1:
                        runHistory = _c.sent();
                        return [2 /*return*/, runHistory.run_histories];
                }
            });
        });
    };
    RunsService.prototype.getLocations = function (id, _a) {
        var _b = _a === void 0 ? {} : _a, signal = _b.signal;
        return __awaiter(this, void 0, void 0, function () {
            var runLocations;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0: return [4 /*yield*/, this.service.handleAuthorizedRequest({
                            route: exports.Routes.GET_RUN_LOCATIONS,
                            extractor: runs_consts_1.runsLocationsExtractor,
                            exceptionProducer: BringgException_1.BringgException.serviceException('Failed to get run locations'),
                            routeParams: { id: id },
                            signal: signal
                        })];
                    case 1:
                        runLocations = _c.sent();
                        return [2 /*return*/, runLocations.run_locations];
                }
            });
        });
    };
    RunsService.prototype.getCashout = function (id, _a) {
        var _b = _a === void 0 ? {} : _a, signal = _b.signal;
        return __awaiter(this, void 0, void 0, function () {
            var runLocations;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0: return [4 /*yield*/, this.service.handleAuthorizedRequest({
                            route: exports.Routes.GET_RUN_CASHOUT,
                            extractor: runs_consts_1.runCashoutExtractor,
                            exceptionProducer: BringgException_1.BringgException.serviceException('Failed to get run cashout'),
                            routeParams: { id: id },
                            signal: signal
                        })];
                    case 1:
                        runLocations = _c.sent();
                        return [2 /*return*/, runLocations.run_cashout];
                }
            });
        });
    };
    RunsService.prototype.assignDriver = function (id, userId, targetRun, _a) {
        var _b = _a === void 0 ? {} : _a, signal = _b.signal;
        return __awaiter(this, void 0, void 0, function () {
            var response;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0: return [4 /*yield*/, this.service.handleAuthorizedRequest({
                            route: exports.Routes.ASSIGN_DRIVER,
                            extractor: runs_consts_1.defaultExtractor,
                            exceptionProducer: BringgException_1.BringgException.serviceException('Failed to assign driver to run'),
                            payload: { user_id: userId, target_run: targetRun },
                            routeParams: { id: id },
                            signal: signal
                        })];
                    case 1:
                        response = _c.sent();
                        return [2 /*return*/, response];
                }
            });
        });
    };
    RunsService.prototype.unassignDriver = function (id, userId, _a) {
        var _b = _a === void 0 ? {} : _a, signal = _b.signal;
        return __awaiter(this, void 0, void 0, function () {
            var response;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0: return [4 /*yield*/, this.service.handleAuthorizedRequest({
                            route: exports.Routes.UNASSIGN_DRIVER,
                            extractor: runs_consts_1.defaultExtractor,
                            exceptionProducer: BringgException_1.BringgException.serviceException('Failed to assign driver to run'),
                            payload: { user_id: userId },
                            routeParams: { id: id },
                            signal: signal
                        })];
                    case 1:
                        response = _c.sent();
                        return [2 /*return*/, response];
                }
            });
        });
    };
    RunsService.prototype.assignVehicles = function (id, vehicleId, tasks, _a) {
        var _b = _a === void 0 ? {} : _a, signal = _b.signal;
        return __awaiter(this, void 0, void 0, function () {
            var response;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0: return [4 /*yield*/, this.service.handleAuthorizedRequest({
                            route: exports.Routes.ASSIGN_VEHICLES,
                            extractor: runs_consts_1.defaultExtractor,
                            exceptionProducer: BringgException_1.BringgException.serviceException('Failed to assign vehicles to run'),
                            payload: { vehicle_id: vehicleId, tasks: tasks },
                            routeParams: { id: id },
                            signal: signal
                        })];
                    case 1:
                        response = _c.sent();
                        return [2 /*return*/, response];
                }
            });
        });
    };
    RunsService.prototype.unassignVehicles = function (id, _a) {
        var _b = _a === void 0 ? {} : _a, signal = _b.signal;
        return __awaiter(this, void 0, void 0, function () {
            var response;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0: return [4 /*yield*/, this.service.handleAuthorizedRequest({
                            route: exports.Routes.UNASSIGN_VEHICLES,
                            extractor: runs_consts_1.defaultExtractor,
                            exceptionProducer: BringgException_1.BringgException.serviceException('Failed to unassign vehicles from run'),
                            payload: {},
                            routeParams: { id: id },
                            signal: signal
                        })];
                    case 1:
                        response = _c.sent();
                        return [2 /*return*/, response];
                }
            });
        });
    };
    RunsService.prototype.bulkClose = function (runIds, _a) {
        var _b = _a === void 0 ? {} : _a, signal = _b.signal;
        return __awaiter(this, void 0, void 0, function () {
            var runBulkClose;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0: return [4 /*yield*/, this.service.handleAuthorizedRequest({
                            route: exports.Routes.BULK_CLOSE,
                            extractor: runs_consts_1.defaultExtractor,
                            exceptionProducer: BringgException_1.BringgException.serviceException('Failed to bulk close runs'),
                            payload: { run_ids: runIds },
                            signal: signal
                        })];
                    case 1:
                        runBulkClose = _c.sent();
                        return [2 /*return*/, runBulkClose];
                }
            });
        });
    };
    RunsService.prototype.markDonePlanning = function (runIds, _a) {
        var _b = _a === void 0 ? {} : _a, signal = _b.signal;
        return __awaiter(this, void 0, void 0, function () {
            var markDonePlanning;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0: return [4 /*yield*/, this.service.handleAuthorizedRequest({
                            route: exports.Routes.MARK_DONE_PLANNING,
                            extractor: runs_consts_1.defaultExtractor,
                            exceptionProducer: BringgException_1.BringgException.serviceException('Failed to mark done planning for runs'),
                            payload: { run_ids: runIds },
                            signal: signal
                        })];
                    case 1:
                        markDonePlanning = _c.sent();
                        return [2 /*return*/, markDonePlanning];
                }
            });
        });
    };
    RunsService.prototype.getActualBreaks = function (runIds, _a) {
        var _b = _a === void 0 ? {} : _a, signal = _b.signal;
        return __awaiter(this, void 0, void 0, function () {
            var actualBreaksByRunIdResponse;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0: return [4 /*yield*/, this.service.handleAuthorizedRequest({
                            route: exports.Routes.GET_ACTUAL_BREAKS,
                            extractor: runs_consts_1.defaultExtractor,
                            exceptionProducer: BringgException_1.BringgException.serviceException('Failed to get actual breaks of runs'),
                            payload: {},
                            routeParams: {},
                            queryString: { run_ids: runIds },
                            signal: signal
                        })];
                    case 1:
                        actualBreaksByRunIdResponse = _c.sent();
                        return [2 /*return*/, actualBreaksByRunIdResponse];
                }
            });
        });
    };
    return RunsService;
}());
exports.RunsService = RunsService;
//# sourceMappingURL=runs.service.js.map