"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports._private = exports.SMS = exports.EMAIL = void 0;
exports.register = register;
exports.associate_named_user = associate_named_user;
exports.setCustomEvent = setCustomEvent;
exports.setBatchCustomEvent = setBatchCustomEvent;
exports.setAttribute = setAttribute;
exports.getChannelId = getChannelId;
exports.manageTags = manageTags;
exports.map_endpoint = map_endpoint;
exports.EMAIL = 'email';
exports.SMS = 'sms';
function register(request, settings, payload, old_channel) {
    let address_to_use = payload.channel_object.address;
    const channel_type = payload.channel_type ?? exports.EMAIL;
    const endpoint = map_endpoint(settings.endpoint);
    let register_uri = `${endpoint}/api/channels/email`;
    if (old_channel && payload.channel_object.new_address) {
        register_uri = `${endpoint}/api/channels/email/replace/${old_channel}`;
        address_to_use = payload.channel_object.new_address;
    }
    let country_language = null;
    if (payload.locale && payload.locale.length > 0) {
        country_language = _extract_country_language(payload.locale);
    }
    let locale_country = '';
    let locale_language = '';
    if (Array.isArray(country_language) && country_language.length === 2) {
        locale_language = country_language[0];
        locale_country = country_language[1];
    }
    if (channel_type == exports.SMS) {
        register_uri = `${endpoint}/api/channels/sms`;
        const sms_register_payload = {
            msisdn: address_to_use
        };
        if (payload.channel_object.sms_opted_in) {
            sms_register_payload.opted_in = _parse_and_format_date(payload.channel_object.sms_opted_in);
        }
        if (payload.sms_sender) {
            sms_register_payload.sender = payload.sms_sender;
        }
        if (locale_language) {
            sms_register_payload.locale_language = locale_language;
        }
        if (locale_country) {
            sms_register_payload.locale_country = locale_country;
        }
        if (payload.timezone) {
            sms_register_payload.timezone = payload.timezone;
        }
        return do_request(request, register_uri, sms_register_payload);
    }
    else {
        const email_register_payload = {
            channel: {
                type: channel_type,
                address: address_to_use
            }
        };
        email_register_payload.channel.type = 'email';
        if (payload.channel_object.suppression_state) {
            email_register_payload.channel.suppression_state = payload.channel_object.suppression_state;
        }
        if (payload.channel_object.commercial_opted_in) {
            email_register_payload.channel.commercial_opted_in = _parse_and_format_date(payload.channel_object.commercial_opted_in);
        }
        if (payload.channel_object.commercial_opted_out) {
            email_register_payload.channel.commercial_opted_out = _parse_and_format_date(payload.channel_object.commercial_opted_out);
        }
        if (payload.channel_object.click_tracking_opted_in) {
            email_register_payload.channel.commercial_opted_in = _parse_and_format_date(payload.channel_object.click_tracking_opted_in);
        }
        if (payload.channel_object.click_tracking_opted_out) {
            email_register_payload.channel.click_tracking_opted_in = _parse_and_format_date(payload.channel_object.click_tracking_opted_out);
        }
        if (payload.channel_object.open_tracking_opted_in) {
            email_register_payload.channel.open_tracking_opted_in = _parse_and_format_date(payload.channel_object.open_tracking_opted_in);
        }
        if (payload.channel_object.open_tracking_opted_out) {
            email_register_payload.channel.open_tracking_opted_out = _parse_and_format_date(payload.channel_object.open_tracking_opted_out);
        }
        if (payload.channel_object.transactional_opted_in) {
            email_register_payload.channel.transactional_opted_in = _parse_and_format_date(payload.channel_object.transactional_opted_in);
        }
        if (payload.channel_object.transactional_opted_out) {
            email_register_payload.channel.transactional_opted_out = _parse_and_format_date(payload.channel_object.transactional_opted_out);
        }
        if (locale_language) {
            email_register_payload.channel.locale_language = locale_language;
        }
        if (locale_country) {
            email_register_payload.channel.locale_country = locale_country;
        }
        if (payload.timezone) {
            email_register_payload.channel.timezone = payload.timezone;
        }
        return do_request(request, register_uri, email_register_payload);
    }
}
function associate_named_user(request, settings, channel_id, named_user_id, channel_type) {
    const endpoint = map_endpoint(settings.endpoint);
    const uri = `${endpoint}/api/named_users/associate`;
    const associate_payload = {
        channel_id: channel_id,
        device_type: `${channel_type}`,
        named_user_id: named_user_id
    };
    return do_request(request, uri, associate_payload);
}
function setCustomEvent(request, settings, payload) {
    const endpoint = map_endpoint(settings.endpoint);
    const uri = `${endpoint}/api/custom-events`;
    const airship_payload = _build_custom_event_object(payload);
    return do_request(request, uri, [airship_payload]);
}
function setBatchCustomEvent(request, settings, payloads) {
    const endpoint = map_endpoint(settings.endpoint);
    const uri = `${endpoint}/api/custom-events`;
    const airship_payload = [];
    for (let i = 0; i < payloads.length; i++) {
        airship_payload.push(_build_custom_event_object(payloads[i]));
    }
    return do_request(request, uri, airship_payload);
}
function setAttribute(request, settings, payload) {
    const endpoint = map_endpoint(settings.endpoint);
    const uri = `${endpoint}/api/channels/attributes`;
    const attributes = _build_attributes_object(payload);
    const airship_payload = {
        attributes: attributes,
        audience: {
            named_user_id: `${payload.named_user_id}`
        }
    };
    return do_request(request, uri, airship_payload);
}
function getChannelId(request, settings, emailAddress) {
    const endpoint = map_endpoint(settings.endpoint);
    const uri = `${endpoint}/api/channels/email/${emailAddress}`;
    return request(uri, { method: 'GET' });
}
function manageTags(request, settings, payload) {
    const endpoint = map_endpoint(settings.endpoint);
    const uri = `${endpoint}/api/named_users/tags`;
    const airship_payload = _build_tags_object(payload);
    return do_request(request, uri, airship_payload);
}
function do_request(request, uri, payload) {
    return request(uri, {
        method: 'POST',
        json: payload
    });
}
function map_endpoint(region) {
    if (region === 'EU') {
        return 'https://go.airship.eu';
    }
    else {
        return 'https://go.urbanairship.com';
    }
}
function _build_custom_event_object(payload) {
    if (payload.properties) {
        payload.properties.source = 'Segment';
    }
    else {
        payload.properties = {
            source: 'Segment'
        };
    }
    const airship_payload = {
        occurred: _validate_timestamp(payload.occurred),
        user: {
            named_user_id: payload.named_user_id
        },
        body: {
            name: payload.name.toLowerCase(),
            interaction_type: 'cdp',
            properties: payload.properties
        }
    };
    return airship_payload;
}
function _build_attributes_object(payload) {
    const attributes_list = [];
    const attributes = payload.attributes || {};
    for (const key in attributes) {
        attributes_list.push(_build_attribute(key, attributes[key], payload.occurred));
    }
    return attributes_list;
}
function _build_attribute(attribute_key, attribute_value, occurred) {
    let adjustedDate = null;
    if (typeof attribute_value == 'string') {
        adjustedDate = _parse_date(attribute_value);
    }
    if (['home_phone', 'work_phone', 'mobile_phone'].includes(attribute_key) && typeof attribute_value == 'string') {
        attribute_value = parseInt(attribute_value.replace(/[^0-9]/g, ''));
    }
    const attribute = {
        action: 'set',
        key: attribute_key,
        timestamp: _validate_timestamp(occurred)
    };
    if (attribute_value == null || (typeof attribute_value == 'string' && attribute_value.length === 0)) {
        attribute.action = 'remove';
    }
    else if (adjustedDate !== null) {
        attribute.action = 'set';
        attribute.value = adjustedDate.toISOString().split('.')[0];
    }
    else {
        attribute.action = 'set';
        attribute.value = attribute_value;
    }
    return attribute;
}
function _build_tags_object(payload) {
    const tags_to_add = [];
    const tags_to_remove = [];
    const tag_group = payload.tag_group;
    const properties = payload.tags || {};
    for (const [k, v] of Object.entries(properties)) {
        if (typeof v == 'boolean') {
            if (v) {
                tags_to_add.push(k);
            }
            else {
                tags_to_remove.push(k);
            }
        }
        else if (typeof v == 'string' && ['true', 'false'].includes(v.toString().toLowerCase())) {
            if (v.toLowerCase() === 'true') {
                tags_to_add.push(k);
            }
            else {
                tags_to_remove.push(k);
            }
        }
    }
    const airship_payload = { audience: {} };
    airship_payload.audience = {
        named_user_id: payload.named_user_id
    };
    if (tags_to_add.length > 0) {
        airship_payload.add = { [tag_group]: tags_to_add };
    }
    if (tags_to_remove.length > 0) {
        airship_payload.remove = { [tag_group]: tags_to_remove };
    }
    return airship_payload;
}
function _validate_timestamp(timestamp) {
    const payload_time_stamp = new Date(timestamp);
    const three_months_ago = new Date();
    three_months_ago.setDate(three_months_ago.getDate() - 90);
    if (three_months_ago > payload_time_stamp) {
        return false;
    }
    else {
        return payload_time_stamp.toISOString().split('.')[0];
    }
}
function _parse_and_format_date(date_string) {
    const date_obj = _parse_date(date_string);
    if (date_obj) {
        return date_obj.toISOString().split('.')[0];
    }
    else {
        return date_string;
    }
}
function _parse_date(attribute_value) {
    if (attribute_value.length < 8) {
        return null;
    }
    const date = new Date(attribute_value);
    if (!isNaN(date.getTime())) {
        return date;
    }
    return null;
}
function _extract_country_language(locale) {
    const country_language = locale.split('-');
    return country_language;
}
exports._private = {
    _build_custom_event_object,
    _build_attributes_object,
    _build_attribute,
    _build_tags_object,
    _parse_date,
    _parse_and_format_date,
    _validate_timestamp
};
//# sourceMappingURL=utilities.js.map