"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 __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
exports.createNewFlagsmithInstance = exports.globalFlagsmith = void 0;
const axios_1 = __importDefault(require("axios"));
let defaultEnvironmentKey = 'hXgU8Wc8pwuGNq9ms5q9Hh';
if (typeof process !== 'undefined') {
    if ((_a = process === null || process === void 0 ? void 0 : process.env) === null || _a === void 0 ? void 0 : _a.FLAGSMITH_ENVIRONMENT_KEY) {
        defaultEnvironmentKey = process.env.FLAGSMITH_ENVIRONMENT_KEY;
    }
}
function normalizeFlags(respFlags = []) {
    const formattedFlags = {};
    respFlags.forEach((respFlag) => {
        formattedFlags[respFlag.feature.name] = {
            enabled: respFlag.enabled,
            value: respFlag.feature_state_value,
        };
    });
    return formattedFlags;
}
class Flagsmith {
    constructor(environmentKey = defaultEnvironmentKey) {
        this.flags = {};
        this.environmentKey = null;
        this.environmentKey = environmentKey;
        this.identify = this.identify.bind(this);
        this.getValue = this.getValue.bind(this);
        this.hasFeature = this.hasFeature.bind(this);
        this.getAllFlags = this.getAllFlags.bind(this);
    }
    identify(uniqueIdentifier, traitsObj = {}, forceEvaluate = false) {
        return __awaiter(this, void 0, void 0, function* () {
            const traits = JSON.parse(JSON.stringify(traitsObj));
            const formattedTraits = Object.entries(traits).map((tuple) => ({
                trait_key: tuple[0],
                trait_value: tuple[1],
            }));
            try {
                const randomChars = `_${(Math.random() + 1)
                    .toString(36)
                    .substring(2)}`; // Gives string like _26ejlqigw9
                const flagsmithResponse = yield axios_1.default.post('https://api.flagsmith.com/api/v1/identities/', {
                    identifier: uniqueIdentifier + (forceEvaluate ? randomChars : ''),
                    traits: formattedTraits,
                }, {
                    headers: {
                        'Content-Type': 'application/json',
                        'X-Environment-Key': this.environmentKey,
                    },
                });
                this.flags = normalizeFlags(flagsmithResponse.data.flags || []);
            }
            catch (ex) {
                // console.error('Flagsmith identify failed!!');
            }
            return this.flags;
        });
    }
    getValue(featureFlagName) {
        return (this.flags &&
            this.flags[featureFlagName] &&
            this.flags[featureFlagName].value);
    }
    hasFeature(featureFlagName) {
        return (this.flags &&
            this.flags[featureFlagName] &&
            this.flags[featureFlagName].enabled);
    }
    getAllFlags() {
        return this.flags;
    }
}
const globalFlagsmith = new Flagsmith();
exports.globalFlagsmith = globalFlagsmith;
function createNewFlagsmithInstance(environmentKey) {
    return new Flagsmith(environmentKey);
}
exports.createNewFlagsmithInstance = createNewFlagsmithInstance;
//# sourceMappingURL=flagsmith.js.map