"use strict";
/**
 *  Indication Controller
 *
 *  Copyright (C) 2010-2020 R-T Specialty, LLC.
 *
 *  This file is part of the Liza Data Collection Framework.
 *
 *  liza is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
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 (_) 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 };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.indication = void 0;
var numeric_1 = require("../../numeric");
var RaterFactory_1 = require("../program/RaterFactory");
var MongoServerDao_1 = require("../../server/db/MongoServerDao");
var HttpClient_1 = require("../../system/network/HttpClient");
/* eslint-disable @typescript-eslint/no-var-requires */
var createQuote = require('../../server/quote/ServerSideQuote');
var createBucket = require('../../bucket/QuoteDataBucket');
/* eslint-enable @typescript-eslint/no-var-requires */
exports.indication = {
    /**
     * Create a new indication
     *
     * @param emitter         - event emitter
     * @param http            - HTTP client
     * @param program_factory - used to generate programs on demand
     * @param quote_factory   - create quotes
     * @param request         - request object
     * @param response        - response object
     */
    create: function (emitter) { return function (http) { return function (program_factory) { return function (quote_factory) { return function (rater) { return function (dao) { return function (request, response) { return __awaiter(void 0, void 0, void 0, function () {
        var webhook, _a, request_bucket, request_session, meta, message, session, quote_maker, doc_data, _b, bucket, program, quote, rdata, delta, data, webhook_response, e_1;
        return __generator(this, function (_c) {
            switch (_c.label) {
                case 0:
                    webhook = '';
                    _a = request.body, request_bucket = _a.bucket, request_session = _a.session, meta = _a.metabucket;
                    if (request.query && request.query.callback) {
                        webhook = decodeURIComponent(request.query.callback);
                    }
                    try {
                        http.validateUrl(webhook);
                        RaterFactory_1.validate_session_template(request_session);
                    }
                    catch (e) {
                        message = e instanceof HttpClient_1.InvalidUrlError
                            ? 'Request must contain a valid webhook URL.'
                            : e.message;
                        response.status(422).send({ message: message });
                        emitter.emit('error', e);
                        return [2 /*return*/];
                    }
                    // Send acceptance back to originator
                    response.status(202).send({ message: 'Request received.' });
                    emitter.emit('response-sent', { http_code: 202 });
                    session = RaterFactory_1.getDummySession(request_session);
                    quote_maker = function (program) { return function (id) {
                        var quote = createQuote(id, createBucket(), program);
                        quote.setMetabucket(createBucket());
                        quote.setRateBucket(createBucket());
                        return quote;
                    }; };
                    doc_data = {
                        agentId: session.agentId(),
                        agentName: session.agentName(),
                        agentEntityId: session.agentEntityId(),
                        startDate: numeric_1.ts_ctor(),
                    };
                    _c.label = 1;
                case 1:
                    _c.trys.push([1, 7, , 8]);
                    _b = program_factory.createProgram(request_bucket), bucket = _b.bucket, program = _b.program;
                    return [4 /*yield*/, quote_factory(dao)(quote_maker)(program)(session)(doc_data)];
                case 2:
                    quote = (_c.sent()).setData(bucket.getData());
                    return [4 /*yield*/, rater.rate(quote, session)];
                case 3:
                    rdata = _c.sent();
                    delta = {
                        'rdelta.data': {
                            data: {},
                            concluding_save: false,
                            timestamp: numeric_1.ts_ctor(),
                            step_id: -1,
                        },
                    };
                    data = {
                        programId: program.getId(),
                        // TODO: rate_pending can be automatically set when RatingService is used
                        'ratedata.__rate_pending': [0],
                        data: bucket.getData(),
                    };
                    return [4 /*yield*/, MongoServerDao_1.asyncServerDao(dao).saveQuote(quote, data, delta)];
                case 4:
                    _c.sent();
                    return [4 /*yield*/, MongoServerDao_1.asyncServerDao(dao).saveQuoteMetaDirect(quote, meta !== null && meta !== void 0 ? meta : {})];
                case 5:
                    _c.sent();
                    emitter.emit('quote-save-success', { quote_id: quote.getId() });
                    emitter.emit('callback-sent', { target: webhook });
                    return [4 /*yield*/, http.post(webhook, {
                            bucket: quote.getBucket().getData(),
                            rdata: rdata,
                        })];
                case 6:
                    webhook_response = _c.sent();
                    if (!webhook_response.ok) {
                        throw new HttpClient_1.HttpBadResponseError("Webhook response returned error code: " + response.status);
                    }
                    emitter.emit('callback-success', { response: webhook_response });
                    return [3 /*break*/, 8];
                case 7:
                    e_1 = _c.sent();
                    if (e_1 instanceof RaterFactory_1.RateError) {
                        emitter.emit('rate-error', { msg: e_1.message });
                    }
                    else if (e_1 instanceof MongoServerDao_1.ServerDaoSaveError) {
                        emitter.emit('quote-save-failure', { quote_id: e_1.id });
                    }
                    else if (e_1 instanceof HttpClient_1.HttpBadResponseError) {
                        emitter.emit('callback-failure', { error: e_1 });
                    }
                    else {
                        emitter.emit('error', e_1);
                    }
                    return [3 /*break*/, 8];
                case 8: return [2 /*return*/];
            }
        });
    }); }; }; }; }; }; }; },
};
//# sourceMappingURL=data:application/json;base64, 