"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseSections = parseSections;
exports.addUpdateEvents = addUpdateEvents;
const actions_core_1 = require("@segment/actions-core");
const get_1 = __importDefault(require("lodash/get"));
function parseSections(section, nestDepth) {
    const parseResults = {};
    try {
        if (nestDepth > 10)
            throw new actions_core_1.IntegrationError('Event data exceeds nesting depth. Use Mapping to avoid nesting data attributes more than 3 levels deep', 'NESTING_DEPTH_EXCEEDED', 400);
        for (const key of Object.keys(section)) {
            if (typeof section[key] === 'object') {
                nestDepth++;
                const nested = parseSections(section[key], nestDepth);
                for (const nestedKey of Object.keys(nested)) {
                    parseResults[`${key}.${nestedKey}`] = nested[nestedKey];
                }
            }
            else {
                parseResults[key] = section[key];
            }
        }
    }
    catch (e) {
        throw new actions_core_1.IntegrationError(`Unexpected Exception while parsing Event payload.\n ${e}`, 'UNEXPECTED_EVENT_PARSING_EXCEPTION', 400);
    }
    return parseResults;
}
function addUpdateEvents(payload, email, limit) {
    let eventName = '';
    let eventValue = '';
    let xmlRows = '';
    const eventSource = (0, get_1.default)(payload, 'type', 'Null') + ' Event';
    const timestamp = (0, get_1.default)(payload, 'timestamp', 'Null');
    let propertiesTraitsKV = {};
    try {
        if (payload.key_value_pairs)
            propertiesTraitsKV = {
                ...propertiesTraitsKV,
                ...parseSections(payload.key_value_pairs, 0)
            };
        if (payload.array_data)
            propertiesTraitsKV = {
                ...propertiesTraitsKV,
                ...parseSections(payload.array_data, 0)
            };
        if (payload.traits)
            propertiesTraitsKV = {
                ...propertiesTraitsKV,
                ...parseSections(payload.traits, 0)
            };
        if (payload.properties)
            propertiesTraitsKV = {
                ...propertiesTraitsKV,
                ...parseSections(payload.properties, 0)
            };
        if (payload.context)
            propertiesTraitsKV = {
                ...propertiesTraitsKV,
                ...parseSections(payload.context, 0)
            };
    }
    catch (e) {
        throw new actions_core_1.IntegrationError('Unexpected Exception processing payload \n ${e}', 'UNEXPECTED_EXCEPTION_PROCESSING_PAYLOAD', 400);
    }
    const l = Object.keys(propertiesTraitsKV).length;
    if (l > limit) {
        throw new actions_core_1.IntegrationError(`There are ${l} Attributes in this Event. This exceeds the max of ${limit}. Use Mapping to limit the number of Attributes and thereby reduce the Campaign Relational Table Rows consumed.`, 'EXCEEDS_MAX_PROPERTIES_MAX', 400);
    }
    let ak = '';
    let av = '';
    const getValue = (o, part) => Object.entries(o).find(([k, _v]) => k.includes(part))?.[1];
    const getKey = (o, part) => Object.entries(o).find(([k, _v]) => k.includes(part))?.[0];
    if (getValue(propertiesTraitsKV, 'computation_class')?.toLowerCase() === 'audience') {
        ak = getValue(propertiesTraitsKV, 'computation_key');
        av = getValue(propertiesTraitsKV, `${ak}`);
        let x = getKey(propertiesTraitsKV, 'computation_class');
        delete propertiesTraitsKV[`${x}`];
        x = getKey(propertiesTraitsKV, 'computation_key');
        delete propertiesTraitsKV[`${x}`];
        delete propertiesTraitsKV[`${ak}`];
    }
    if (getValue(propertiesTraitsKV, 'audience_key')) {
        ak = getValue(propertiesTraitsKV, 'audience_key');
        av = getValue(propertiesTraitsKV, `${ak}`);
        const x = getKey(propertiesTraitsKV, 'audience_key');
        delete propertiesTraitsKV[`${x}`];
        delete propertiesTraitsKV[`${ak}`];
    }
    if (av !== '') {
        let audiStatus = av;
        eventValue = audiStatus;
        audiStatus = audiStatus.toString().toLowerCase();
        if (audiStatus === 'true')
            eventValue = 'Audience Entered';
        if (audiStatus === 'false')
            eventValue = 'Audience Exited';
        eventName = ak;
        xmlRows += `  
      <ROW>
      <COLUMN name="EMAIL">           <![CDATA[${email}]]></COLUMN>
      <COLUMN name="EventSource">     <![CDATA[${eventSource}]]></COLUMN>  
      <COLUMN name="EventName">       <![CDATA[${eventName}]]></COLUMN>
      <COLUMN name="EventValue">      <![CDATA[${eventValue}]]></COLUMN>
      <COLUMN name="Event Timestamp"> <![CDATA[${timestamp}]]></COLUMN>
      </ROW>`;
    }
    for (const e in propertiesTraitsKV) {
        const eventName = e;
        const eventValue = propertiesTraitsKV[e];
        xmlRows += `
     <ROW>
     <COLUMN name="Email">           <![CDATA[${email}]]></COLUMN>
     <COLUMN name="EventSource">     <![CDATA[${eventSource}]]></COLUMN>  
     <COLUMN name="EventName">       <![CDATA[${eventName}]]></COLUMN>
     <COLUMN name="EventValue">      <![CDATA[${eventValue}]]></COLUMN>
     <COLUMN name="Event Timestamp"> <![CDATA[${timestamp}]]></COLUMN>
     </ROW>`;
    }
    return xmlRows;
}
//# sourceMappingURL=eventprocessing.js.map