"use strict";
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 });
// Require the LUSID SDK and libraries
var api_1 = require("../../api");
var clientBuilder_1 = require("./clientBuilder");
var FileType;
(function (FileType) {
    FileType["Json"] = "Json";
    FileType["Csv"] = "Csv";
})(FileType || (FileType = {}));
var uuid4 = require('uuid/v4');
var csv = require('csvtojson');
var uniqueScope = 'Performance' + uuid4();
var debugHeaders = ['lusid-meta-requestid'];
// Create a custom property using the LUSID model
var sectorDataTypeId = new api_1.ResourceId();
sectorDataTypeId.scope = "system";
sectorDataTypeId.code = "string";
// Create a property definition request to define a new property in LUSID
var sectorProp = new api_1.CreatePropertyDefinitionRequest();
sectorProp.domain = api_1.CreatePropertyDefinitionRequest.DomainEnum.Instrument;
sectorProp.scope = uniqueScope;
sectorProp.code = 'Sector';
sectorProp.valueRequired = true;
sectorProp.displayName = 'Sector';
sectorProp.dataTypeId = sectorDataTypeId;
sectorProp.lifeTime = api_1.CreatePropertyDefinitionRequest.LifeTimeEnum.TimeVariant;
describe('Load Instrument Master', function () {
    it('Should upsert instruments into LUSID', function () { return __awaiter(void 0, void 0, void 0, function () {
        var instruments, err_1;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    _a.trys.push([0, 3, , 4]);
                    return [4 /*yield*/, getInstrumentsFromFile('./instruments.json', FileType.Json)];
                case 1:
                    instruments = _a.sent();
                    return [4 /*yield*/, upsertInstruments(instruments)];
                case 2:
                    _a.sent();
                    return [3 /*break*/, 4];
                case 3:
                    err_1 = _a.sent();
                    throw new Error("Failed to upsert instruments. Error: " + err_1.toString());
                case 4: return [2 /*return*/];
            }
        });
    }); });
});
describe('Create property definitions', function () {
    it('Should create a sector property in LUSID', function () { return __awaiter(void 0, void 0, void 0, function () {
        var err_2;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    _a.trys.push([0, 2, , 3]);
                    return [4 /*yield*/, createProperty(sectorProp)];
                case 1:
                    _a.sent();
                    return [3 /*break*/, 3];
                case 2:
                    err_2 = _a.sent();
                    throw new Error("Failed to create the sector property. Error: " + err_2.toString());
                case 3: return [2 /*return*/];
            }
        });
    }); });
});
describe('Add properties on instruments', function () {
    it('Should add the sector property on each instrument', function () { return __awaiter(void 0, void 0, void 0, function () {
        var requests, err_3;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    _a.trys.push([0, 3, , 4]);
                    return [4 /*yield*/, getPropertyRequestsFromFile('./instrument-properties.json', 'Sector', FileType.Json)];
                case 1:
                    requests = _a.sent();
                    return [4 /*yield*/, upsertInstrumentProperties(requests)];
                case 2:
                    _a.sent();
                    return [3 /*break*/, 4];
                case 3:
                    err_3 = _a.sent();
                    throw new Error("Failed to add sector property to instruments. Error: " + err_3.toString());
                case 4: return [2 /*return*/];
            }
        });
    }); });
});
// Import your instruments from a CSV file
function loadFromCsv(filePath) {
    return __awaiter(this, void 0, void 0, function () {
        var instruments, err_4;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    _a.trys.push([0, 2, , 3]);
                    return [4 /*yield*/, csv().fromFile(filePath)];
                case 1:
                    instruments = _a.sent();
                    return [2 /*return*/, instruments];
                case 2:
                    err_4 = _a.sent();
                    throw new Error("Failed to load instruments from CSV. Error: " + err_4.toString());
                case 3: return [2 /*return*/];
            }
        });
    });
}
// Import your instruments from a JSON file
function loadFromJson(filePath) {
    return __awaiter(this, void 0, void 0, function () {
        var instruments;
        return __generator(this, function (_a) {
            try {
                instruments = require(filePath);
                return [2 /*return*/, instruments];
            }
            catch (err) {
                throw new Error("Failed to load instruments from JSON. Error: " + err.toString());
            }
            return [2 /*return*/];
        });
    });
}
// Upsert a set of instrument definitions into LUSID
function upsertInstruments(instruments) {
    var _a;
    return __awaiter(this, void 0, void 0, function () {
        var body, res, err_5;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    body = {};
                    instruments.forEach(function (instrument) {
                        body[instrument.name] = instrument;
                    });
                    _b.label = 1;
                case 1:
                    _b.trys.push([1, 3, , 4]);
                    return [4 /*yield*/, clientBuilder_1.client.api.instruments.upsertInstruments(body, uniqueScope)];
                case 2:
                    res = _b.sent();
                    getLoggingInfo((_a = res === null || res === void 0 ? void 0 : res.response) === null || _a === void 0 ? void 0 : _a.rawHeaders, debugHeaders, 'upsertInstruments');
                    return [2 /*return*/, res.body];
                case 3:
                    err_5 = _b.sent();
                    throw new Error("Failed to upsert instruments. Error: " + err_5.toString());
                case 4: return [2 /*return*/];
            }
        });
    });
}
// Use your client to call LUSID and create a new property
function createProperty(propertyDefintion) {
    var _a;
    return __awaiter(this, void 0, void 0, function () {
        var res, err_6;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    _b.trys.push([0, 2, , 3]);
                    return [4 /*yield*/, clientBuilder_1.client.api.propertyDefinitions.createPropertyDefinition(propertyDefintion)];
                case 1:
                    res = _b.sent();
                    getLoggingInfo((_a = res === null || res === void 0 ? void 0 : res.response) === null || _a === void 0 ? void 0 : _a.rawHeaders, debugHeaders, 'createPropertyDefinition');
                    return [2 /*return*/, res.body];
                case 2:
                    err_6 = _b.sent();
                    throw new Error("Failed to create property. Error: " + err_6.toString());
                case 3: return [2 /*return*/];
            }
        });
    });
}
// Construct a property that we can add to a LUSID instrument
function buildInstrumentProperty(key, value) {
    var instrumentProperty = new api_1.Property();
    instrumentProperty.key = key;
    var instrumentPropertyValue = new api_1.PropertyValue();
    instrumentPropertyValue.labelValue = value;
    instrumentProperty.value = instrumentPropertyValue;
    return instrumentProperty;
}
// Use your client to add a property to a particular instrument in LUSID
function upsertInstrumentProperties(requests) {
    var _a;
    return __awaiter(this, void 0, void 0, function () {
        var res, err_7;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    _b.trys.push([0, 2, , 3]);
                    return [4 /*yield*/, clientBuilder_1.client.api.instruments.upsertInstrumentsProperties(requests, uniqueScope)];
                case 1:
                    res = _b.sent();
                    getLoggingInfo((_a = res === null || res === void 0 ? void 0 : res.response) === null || _a === void 0 ? void 0 : _a.rawHeaders, debugHeaders, 'upsertInstrumentProperties');
                    return [2 /*return*/, res.body];
                case 2:
                    err_7 = _b.sent();
                    throw new Error("Failed to upsert instrument properties. Error: " + err_7.toString());
                case 3: return [2 /*return*/];
            }
        });
    });
}
// Load our instrument definitions from a file
function getInstrumentsFromFile(filePath, fileType) {
    return __awaiter(this, void 0, void 0, function () {
        var loadFunction, instruments;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    if (fileType == FileType.Json) {
                        loadFunction = loadFromJson(filePath);
                    }
                    else {
                        loadFunction = loadFromCsv(filePath);
                    }
                    return [4 /*yield*/, loadFunction];
                case 1:
                    instruments = _a.sent();
                    return [2 /*return*/, instruments.map(function (instrument) {
                            var definition = new api_1.InstrumentDefinition();
                            var cusipIdentifier = new api_1.InstrumentIdValue();
                            cusipIdentifier.value = instrument.CUSIP;
                            var isinIdentifier = new api_1.InstrumentIdValue();
                            isinIdentifier.value = instrument.ISIN;
                            var tickerIdentifier = new api_1.InstrumentIdValue();
                            tickerIdentifier.value = instrument.Ticker;
                            var figiIdentifier = new api_1.InstrumentIdValue();
                            figiIdentifier.value = instrument.Figi;
                            definition.name = instrument.Name;
                            definition.identifiers = {
                                "Cusip": cusipIdentifier,
                                "Isin": isinIdentifier,
                                "Ticker": tickerIdentifier,
                                "Figi": figiIdentifier
                            };
                            return definition;
                        })];
            }
        });
    });
}
function getPropertyRequestsFromFile(filePath, propertyName, fileType) {
    return __awaiter(this, void 0, void 0, function () {
        var loadFunction, properties;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    loadFunction = fileType === FileType.Json ? loadFromJson(filePath) : loadFromCsv(filePath);
                    return [4 /*yield*/, loadFunction];
                case 1:
                    properties = _a.sent();
                    return [2 /*return*/, properties.map(function (property) {
                            var instrumentPropertyRequest = new api_1.UpsertInstrumentPropertyRequest();
                            instrumentPropertyRequest.identifierType = "Figi";
                            instrumentPropertyRequest.identifier = property.Figi;
                            instrumentPropertyRequest.properties = [
                                buildInstrumentProperty("Instrument/" + uniqueScope + "/" + propertyName, property[propertyName])
                            ];
                            return instrumentPropertyRequest;
                        })];
            }
        });
    });
}
function getLoggingInfo(headers, keysToSearch, functionCallName) {
    if (headers) {
        var _loop_1 = function (key) {
            var index = headers.findIndex(function (header) { return header === key; });
            if (index > -1) {
                console.log(functionCallName + ": " + headers[index] + ": " + headers[index + 1]);
            }
        };
        for (var _i = 0, keysToSearch_1 = keysToSearch; _i < keysToSearch_1.length; _i++) {
            var key = keysToSearch_1[_i];
            _loop_1(key);
        }
    }
}
//# sourceMappingURL=instrumentMaster.test.js.map