"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PushNotificationBaseClass = exports.FEED_MAP = void 0;
const tslib_1 = require("tslib");
const constants_1 = require("../constants");
const config = require("../config");
const helpers_1 = require("../chat/helpers");
const constants_2 = require("../payloads/constants");
const ethers_1 = require("ethers");
const axios_1 = require("axios");
const viem_1 = require("viem");
const PUSH_CHANNEL = require("../channels");
const helpers_2 = require("../helpers");
const PushAPI_1 = require("../pushapi/PushAPI");
// ERROR CONSTANTS
const ERROR_ACCOUNT_NEEDED = 'Account is required';
const ERROR_SIGNER_NEEDED = 'Signer object is required';
const BROADCAST_TYPE = '*';
const LENGTH_UPPER_LIMIT = 125;
const LENGTH_LOWER_LIMTI = 1;
const SETTING_DELIMITER = '-';
const SETTING_SEPARATOR = '+';
const RANGE_TYPE = 3;
const SLIDER_TYPE = 2;
const BOOLEAN_TYPE = 1;
const DEFAULT_ENABLE_VALUE = '1';
const DEFAULT_TICKER_VALUE = '1';
exports.FEED_MAP = {
    INBOX: false,
    SPAM: true,
};
class PushNotificationBaseClass {
    constructor(signer, env, account) {
        this.signer = signer;
        this.env = env;
        this.guestMode = !!(account && signer);
        this.account = account;
        this.initializeCoreContract({ signer: this.signer, env: this.env });
    }
    initializeCoreContract(options) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            const { env = constants_1.ENV.STAGING, signer = null } = options || {};
            // Derives account from signer if not provided
            let derivedAccount;
            let coreContract;
            if (signer) {
                derivedAccount = yield (0, helpers_1.getAccountAddress)({
                    account: null,
                    signer: signer,
                });
                const pushSigner = new helpers_2.Signer(signer);
                if (pushSigner.isViemSigner(signer)) {
                    const client = (0, viem_1.createPublicClient)({
                        chain: config.TOKEN_VIEM_NETWORK_MAP[env],
                        transport: (0, viem_1.http)(),
                    });
                    coreContract = (0, viem_1.getContract)({
                        abi: config.ABIS.CORE,
                        address: config.CORE_CONFIG[env].EPNS_CORE_CONTRACT,
                        publicClient: client,
                        walletClient: signer,
                    });
                }
                else {
                    coreContract = new ethers_1.ethers.Contract(config.CORE_CONFIG[env].EPNS_CORE_CONTRACT, config.ABIS.CORE, signer);
                }
            }
            // Initialize PushNotifications instance
            this.coreContract = coreContract;
        });
    }
    // check if addresses is supplied either by user or derived from signer object or if its guest mode
    checkUserAddressExists(user) {
        if (!user && !this.account && !this.guestMode)
            throw new Error(ERROR_ACCOUNT_NEEDED);
        return true;
    }
    // checks if the signer object is supplied
    checkSignerObjectExists() {
        if (!this.signer)
            throw new Error(PushAPI_1.PushAPI.ensureSignerMessage());
        return true;
    }
    // get type of notification from recipient
    getNotificationType(recipient, channel) {
        if (recipient.length == 1) {
            if (recipient[0] == BROADCAST_TYPE) {
                return { recipient: channel, type: constants_2.NOTIFICATION_TYPE['BROADCAST'] };
            }
            else {
                return {
                    recipient: recipient[0],
                    type: constants_2.NOTIFICATION_TYPE['TARGETTED'],
                };
            }
        }
        return { recipient, type: constants_2.NOTIFICATION_TYPE['SUBSET'] };
    }
    // get identity type for lowlevel call
    generateNotificationLowLevelPayload({ signer, env, recipients, options, channel, settings, }) {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t;
        if (!channel) {
            channel = `${this.account}`;
        }
        const notificationType = this.getNotificationType(recipients, channel);
        const identityType = constants_2.IDENTITY_TYPE.DIRECT_PAYLOAD;
        // fetch the minimal version based on conifg that was passed
        let index = '';
        if (((_a = options.payload) === null || _a === void 0 ? void 0 : _a.category) && settings) {
            if (settings[options.payload.category - 1].type == SLIDER_TYPE) {
                index =
                    options.payload.category +
                        SETTING_DELIMITER +
                        SLIDER_TYPE +
                        SETTING_DELIMITER +
                        settings[options.payload.category - 1].default;
            }
            if (settings[options.payload.category - 1].type == BOOLEAN_TYPE) {
                index = options.payload.category + SETTING_DELIMITER + BOOLEAN_TYPE;
            }
            if (settings[options.payload.category - 1].type == RANGE_TYPE) {
                index =
                    options.payload.category +
                        SETTING_DELIMITER +
                        RANGE_TYPE +
                        SETTING_DELIMITER +
                        settings[options.payload.category - 1].default.lower;
            }
        }
        const notificationPayload = {
            signer: signer,
            channel: channel,
            type: notificationType.type,
            identityType: identityType,
            notification: options.notification,
            payload: {
                title: (_c = (_b = options.payload) === null || _b === void 0 ? void 0 : _b.title) !== null && _c !== void 0 ? _c : options.notification.title,
                body: (_e = (_d = options.payload) === null || _d === void 0 ? void 0 : _d.body) !== null && _e !== void 0 ? _e : options.notification.body,
                cta: (_g = (_f = options.payload) === null || _f === void 0 ? void 0 : _f.cta) !== null && _g !== void 0 ? _g : '',
                img: (_j = (_h = options.payload) === null || _h === void 0 ? void 0 : _h.embed) !== null && _j !== void 0 ? _j : '',
                hidden: (_k = options.config) === null || _k === void 0 ? void 0 : _k.hidden,
                etime: (_l = options.config) === null || _l === void 0 ? void 0 : _l.expiry,
                silent: (_m = options.config) === null || _m === void 0 ? void 0 : _m.silent,
                additionalMeta: (_o = options.payload) === null || _o === void 0 ? void 0 : _o.meta,
                index: ((_p = options.payload) === null || _p === void 0 ? void 0 : _p.category) ? index : '',
            },
            recipients: notificationType.recipient,
            graph: (_q = options.advanced) === null || _q === void 0 ? void 0 : _q.graph,
            ipfsHash: (_r = options.advanced) === null || _r === void 0 ? void 0 : _r.ipfs,
            env: env,
            chatId: (_s = options.advanced) === null || _s === void 0 ? void 0 : _s.chatid,
            pgpPrivateKey: (_t = options.advanced) === null || _t === void 0 ? void 0 : _t.pgpPrivateKey,
        };
        return notificationPayload;
    }
    // check if the fields are empty
    isEmpty(field) {
        if (field.trim().length == 0) {
            return true;
        }
        return false;
    }
    // check if the length is valid
    isValidLength(data, upperLen = LENGTH_UPPER_LIMIT, lowerLen = LENGTH_LOWER_LIMTI) {
        return data.length >= lowerLen && data.length <= upperLen;
    }
    // check if url is valid
    isValidUrl(urlString) {
        const urlPattern = new RegExp('^((?:https|http):\\/\\/)' + // validate protocol
            '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' + // validate domain name
            '((\\d{1,3}\\.){3}\\d{1,3}))' + // validate OR ip (v4) address
            '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*' + // validate port and path
            '(\\?[;&a-z\\d%_.~+=-]*)?' + // validate query string
            '(\\#[-a-z\\d_]*)?$', 'i'); // validate fragment locator
        return !!urlPattern.test(urlString);
    }
    // check all the fields of channel
    verifyEmptyChannelParameters(options) {
        if (this.isEmpty(options.name)) {
            throw new Error('Channel name cannot be empty');
        }
        else if (this.isEmpty(options.description)) {
            throw new Error('Channel description cannot be empty');
        }
        else if (this.isEmpty(options.icon)) {
            throw new Error('Channel icon cannot be empty');
        }
        else if (this.isEmpty(options.url)) {
            throw new Error('Channel url cannot ne empty');
        }
        else {
            return true;
        }
    }
    // check for valid length and url
    validateParameterLength(options) {
        if (!this.isValidLength(options.name)) {
            throw new Error(`Channel name should not exceed ${LENGTH_UPPER_LIMIT} characters`);
        }
        else if (!this.isValidLength(options.description)) {
            throw new Error(`Channel description should not exceed ${LENGTH_UPPER_LIMIT} characters`);
        }
        else if (!this.isValidLength(options.url) ||
            !this.isValidUrl(options.url)) {
            throw new Error(`Channel url either excees ${LENGTH_UPPER_LIMIT} characters or is not a valid url`);
        }
        else {
            return true;
        }
    }
    validateChannelParameters(options) {
        return (this.verifyEmptyChannelParameters(options) &&
            this.validateParameterLength(options));
    }
    // create contract instance
    createContractInstance(contractAddress, contractABI, network) {
        if (!this.signer) {
            throw new Error('Signer is not provided');
        }
        let contract;
        const pushSigner = this.signer ? new helpers_2.Signer(this.signer) : null;
        if (pushSigner === null || pushSigner === void 0 ? void 0 : pushSigner.isViemSigner(this.signer)) {
            const client = (0, viem_1.createPublicClient)({
                chain: network,
                transport: (0, viem_1.http)(),
            });
            contract = (0, viem_1.getContract)({
                abi: contractABI,
                address: contractAddress,
                publicClient: client,
                walletClient: this.signer,
            });
        }
        else {
            contract = new ethers_1.ethers.Contract(contractAddress, contractABI, this.signer);
        }
        return contract;
    }
    fetchBalance(contract, userAddress) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            if (!this.signer) {
                throw new Error('Signer is not provided');
            }
            let balance;
            const pushSigner = new helpers_2.Signer(this.signer);
            try {
                if (pushSigner.isViemSigner(this.signer)) {
                    balance = BigInt(yield contract.read.balanceOf({
                        args: [userAddress],
                    }));
                }
                else {
                    balance = BigInt(yield contract.balanceOf(userAddress));
                }
                return balance;
            }
            catch (err) {
                throw new Error(JSON.stringify(err));
            }
        });
    }
    fetchAllownace(contract, userAddress, spenderAddress) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            if (!this.signer) {
                throw new Error('Signer is not provided');
            }
            const pushSigner = new helpers_2.Signer(this.signer);
            let allowance;
            try {
                if (!pushSigner.isViemSigner(this.signer)) {
                    allowance = BigInt(yield contract['allowance'](userAddress, spenderAddress));
                }
                else {
                    allowance = BigInt(yield contract.read.allowance({
                        args: [userAddress, spenderAddress],
                    }));
                }
                return allowance;
            }
            catch (error) {
                throw new Error(JSON.stringify(error));
            }
        });
    }
    fetchUpdateCounter(contract, userAddress) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            if (!this.signer) {
                throw new Error('Signer is not provided');
            }
            let count;
            const pushSigner = new helpers_2.Signer(this.signer);
            try {
                if (!pushSigner.isViemSigner(this.signer)) {
                    count = BigInt(yield contract['channelUpdateCounter'](userAddress));
                }
                else {
                    count = BigInt(yield contract.read.channelUpdateCounter({
                        args: [userAddress],
                    }));
                }
                // add one and return the count
                return count + BigInt(1);
            }
            catch (error) {
                throw new Error(JSON.stringify(error));
            }
        });
    }
    approveToken(contract, spenderAddress, amount) {
        var _a, _b;
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            try {
                if (!this.signer) {
                    throw new Error('Signer is not provided');
                }
                const pushSigner = new helpers_2.Signer(this.signer);
                if (!pushSigner.isViemSigner(this.signer)) {
                    if (!this.signer || !this.signer.provider) {
                        throw new Error('ethers provider/signer is not provided');
                    }
                    const approvalTrxPromise = contract['approve'](spenderAddress, amount);
                    const approvalTrx = yield approvalTrxPromise;
                    yield ((_b = (_a = this.signer) === null || _a === void 0 ? void 0 : _a.provider) === null || _b === void 0 ? void 0 : _b.waitForTransaction(approvalTrx.hash));
                }
                else {
                    if (!contract.write) {
                        throw new Error('viem signer is not provided');
                    }
                    const approvalTrxPromise = contract.write.approve({
                        args: [spenderAddress, amount],
                    });
                    const approvalTrxRes = yield approvalTrxPromise;
                }
                return true;
            }
            catch (error) {
                console.error(error);
                return false;
            }
        });
    }
    createChannel(contract, channelType, identityBytes, fees) {
        var _a, _b;
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            let createChannelRes;
            try {
                if (!this.signer) {
                    throw new Error('Signer is not provided');
                }
                const pushSigner = new helpers_2.Signer(this.signer);
                if (!pushSigner.isViemSigner(this.signer)) {
                    const createChannelPromise = contract['createChannelWithPUSH'](channelType, identityBytes, fees, this.getTimeBound(), {
                        gasLimit: 1000000,
                    });
                    const createChannelTrx = yield createChannelPromise;
                    const createChannelTrxStatus = yield ((_b = (_a = this.signer) === null || _a === void 0 ? void 0 : _a.provider) === null || _b === void 0 ? void 0 : _b.waitForTransaction(createChannelTrx.hash));
                    if ((createChannelTrxStatus === null || createChannelTrxStatus === void 0 ? void 0 : createChannelTrxStatus.status) == 0) {
                        throw new Error('Something Went wrong while creating your channel');
                    }
                    createChannelRes = createChannelTrx.hash;
                }
                else {
                    if (!contract.write) {
                        throw new Error('viem signer is not provided');
                    }
                    const createChannelPromise = contract.write.createChannelWithPUSH({
                        args: [channelType, identityBytes, fees, this.getTimeBound()],
                    });
                    createChannelRes = yield createChannelPromise;
                }
                return createChannelRes;
            }
            catch (error) {
                throw new Error(error === null || error === void 0 ? void 0 : error.message);
            }
        });
    }
    updateChannel(contract, account, identityBytes, fees) {
        var _a, _b;
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            let updateChannelRes;
            try {
                if (!this.signer) {
                    throw new Error('Signer is not provided');
                }
                const pushSigner = new helpers_2.Signer(this.signer);
                if (!pushSigner.isViemSigner(this.signer)) {
                    const updateChannelPromise = contract['updateChannelMeta'](account, identityBytes, fees, {
                        gasLimit: 1000000,
                    });
                    const updateChannelTrx = yield updateChannelPromise;
                    const updateChannelTrxStatus = yield ((_b = (_a = this.signer) === null || _a === void 0 ? void 0 : _a.provider) === null || _b === void 0 ? void 0 : _b.waitForTransaction(updateChannelTrx.hash));
                    if ((updateChannelTrxStatus === null || updateChannelTrxStatus === void 0 ? void 0 : updateChannelTrxStatus.status) == 0) {
                        throw new Error('Something Went wrong while updating your channel');
                    }
                    updateChannelRes = updateChannelTrx.hash;
                }
                else {
                    if (!contract.write) {
                        throw new Error('viem signer is not provided');
                    }
                    const updateChannelPromise = contract.write.createChannelWithPUSH({
                        args: [account, identityBytes, fees],
                    });
                    updateChannelRes = yield updateChannelPromise;
                }
                return updateChannelRes;
            }
            catch (error) {
                throw new Error(error === null || error === void 0 ? void 0 : error.message);
            }
        });
    }
    verifyChannel(contract, channelToBeVerified) {
        var _a, _b;
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            try {
                if (!this.signer) {
                    throw new Error('Signer is not provided');
                }
                const pushSigner = new helpers_2.Signer(this.signer);
                let verifyTrxRes;
                if (!pushSigner.isViemSigner(this.signer)) {
                    if (!this.signer.provider) {
                        throw new Error('ethers provider is not provided');
                    }
                    const verifyTrxPromise = contract['verify'](channelToBeVerified);
                    const verifyTrx = yield verifyTrxPromise;
                    yield ((_b = (_a = this.signer) === null || _a === void 0 ? void 0 : _a.provider) === null || _b === void 0 ? void 0 : _b.waitForTransaction(verifyTrx.hash));
                    verifyTrxRes = verifyTrx.hash;
                }
                else {
                    if (!contract.write) {
                        throw new Error('viem signer is not provided');
                    }
                    const verifyTrxPromise = contract.write.verify({
                        args: [channelToBeVerified],
                    });
                    verifyTrxRes = yield verifyTrxPromise;
                }
                return verifyTrxRes;
            }
            catch (error) {
                throw new Error(error.message);
            }
        });
    }
    createChanelSettings(contract, numberOfSettings, settings, description, fees) {
        var _a, _b;
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            try {
                if (!this.signer) {
                    throw new Error('Signer is not provided');
                }
                const pushSigner = new helpers_2.Signer(this.signer);
                let createSettingsRes;
                if (!pushSigner.isViemSigner(this.signer)) {
                    if (!this.signer.provider) {
                        throw new Error('ethers provider is not provided');
                    }
                    const createSettingsPromise = contract['createChannelSettings'](numberOfSettings, settings, description, fees);
                    const createSettings = yield createSettingsPromise;
                    yield ((_b = (_a = this.signer) === null || _a === void 0 ? void 0 : _a.provider) === null || _b === void 0 ? void 0 : _b.waitForTransaction(createSettings.hash));
                    createSettingsRes = createSettings.hash;
                }
                else {
                    if (!contract.write) {
                        throw new Error('viem signer is not provided');
                    }
                    const createSettingsTrxPromise = contract.write.createChannelSettings({
                        args: [numberOfSettings, settings, description, fees],
                    });
                    createSettingsRes = yield createSettingsTrxPromise;
                }
                return createSettingsRes;
            }
            catch (error) {
                throw new Error(error.message);
            }
        });
    }
    addDelegator(contract, delegatee) {
        var _a, _b;
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            try {
                if (!this.signer) {
                    throw new Error('Signer is not provided');
                }
                const pushSigner = new helpers_2.Signer(this.signer);
                let addDelegateRes;
                if (!pushSigner.isViemSigner(this.signer)) {
                    if (!this.signer.provider) {
                        throw new Error('ethers provider is not provided');
                    }
                    const addDelegateTrxPromise = contract['addDelegate'](delegatee);
                    const addDelegateTrx = yield addDelegateTrxPromise;
                    yield ((_b = (_a = this.signer) === null || _a === void 0 ? void 0 : _a.provider) === null || _b === void 0 ? void 0 : _b.waitForTransaction(addDelegateTrx.hash));
                    addDelegateRes = addDelegateTrx.hash;
                }
                else {
                    if (!contract.write) {
                        throw new Error('viem signer is not provided');
                    }
                    const addDelegateTrxPromise = contract.write.addDelegate({
                        args: [delegatee],
                    });
                    addDelegateRes = yield addDelegateTrxPromise;
                }
                return addDelegateRes;
            }
            catch (error) {
                throw new Error(error.message);
            }
        });
    }
    removeDelegator(contract, delegatee) {
        var _a, _b;
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            try {
                if (!this.signer) {
                    throw new Error('Signer is not provided');
                }
                const pushSigner = new helpers_2.Signer(this.signer);
                let removeDelegateRes;
                if (!pushSigner.isViemSigner(this.signer)) {
                    if (!this.signer.provider) {
                        throw new Error('ethers provider is not provided');
                    }
                    const removeDelegateTrxPromise = contract['removeDelegate'](delegatee);
                    const removeDelegateTrx = yield removeDelegateTrxPromise;
                    yield ((_b = (_a = this.signer) === null || _a === void 0 ? void 0 : _a.provider) === null || _b === void 0 ? void 0 : _b.waitForTransaction(removeDelegateTrx.hash));
                    removeDelegateRes = removeDelegateTrx.hash;
                }
                else {
                    if (!contract.write) {
                        throw new Error('viem signer is not provided');
                    }
                    const removeDelegateTrxPromise = contract.write.removeDelegate({
                        args: [delegatee],
                    });
                    removeDelegateRes = yield removeDelegateTrxPromise;
                }
                return removeDelegateRes;
            }
            catch (error) {
                throw new Error(error.message);
            }
        });
    }
    getChainId(signer) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            if (!this.signer) {
                throw new Error('Signer is not provided');
            }
            const pushSigner = new helpers_2.Signer(this.signer);
            return pushSigner.getChainId();
        });
    }
    uploadToIPFSViaPushNode(data) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            try {
                const response = yield axios_1.default.post(`${config.CORE_CONFIG[this.env].API_BASE_URL}/v1/ipfs/upload`, { data });
                return response.data.cid;
            }
            catch (error) {
                throw new Error('Something went wrong while uploading data to IPFS');
            }
        });
    }
    getTimeBound(timeStamp) {
        // for now returns 0 for non-time bound. Later it can be modified to handle time bound channels
        return 0;
    }
    getMinimalSetting(configuration) {
        var _a, _b;
        let notificationSetting = '';
        let notificationSettingDescription = '';
        for (let i = 0; i < configuration.length; i++) {
            const ele = configuration[i];
            if (ele.type == BOOLEAN_TYPE) {
                notificationSetting =
                    notificationSetting +
                        SETTING_SEPARATOR +
                        BOOLEAN_TYPE +
                        SETTING_DELIMITER +
                        ele.default;
            }
            if (ele.type == SLIDER_TYPE) {
                if (ele.data) {
                    const enabled = ele.data && ele.data.enabled != undefined
                        ? Number(ele.data.enabled).toString()
                        : DEFAULT_ENABLE_VALUE;
                    const ticker = (_a = ele.data.ticker) !== null && _a !== void 0 ? _a : DEFAULT_TICKER_VALUE;
                    notificationSetting =
                        notificationSetting +
                            SETTING_SEPARATOR +
                            SLIDER_TYPE +
                            SETTING_DELIMITER +
                            enabled +
                            SETTING_DELIMITER +
                            ele.default +
                            SETTING_DELIMITER +
                            ele.data.lower +
                            SETTING_DELIMITER +
                            ele.data.upper +
                            SETTING_DELIMITER +
                            ticker;
                }
            }
            if (ele.type == RANGE_TYPE) {
                if (ele.default && typeof ele.default == 'object' && ele.data) {
                    const enabled = ele.data && ele.data.enabled != undefined
                        ? Number(ele.data.enabled).toString()
                        : DEFAULT_ENABLE_VALUE;
                    const ticker = (_b = ele.data.ticker) !== null && _b !== void 0 ? _b : DEFAULT_TICKER_VALUE;
                    notificationSetting =
                        notificationSetting +
                            SETTING_SEPARATOR +
                            RANGE_TYPE +
                            SETTING_DELIMITER +
                            enabled +
                            SETTING_DELIMITER +
                            ele.default.lower +
                            SETTING_DELIMITER +
                            ele.default.upper +
                            SETTING_DELIMITER +
                            ele.data.lower +
                            SETTING_DELIMITER +
                            ele.data.upper +
                            SETTING_DELIMITER +
                            ticker;
                }
            }
            notificationSettingDescription =
                notificationSettingDescription + SETTING_SEPARATOR + ele.description;
        }
        return {
            setting: notificationSetting.replace(/^\+/, ''),
            description: notificationSettingDescription.replace(/^\+/, ''),
        };
    }
    getMinimalUserSetting(setting) {
        var _a, _b;
        if (!setting) {
            return null;
        }
        let userSetting = '';
        let numberOfSettings = 0;
        for (let i = 0; i < setting.length; i++) {
            const ele = setting[i];
            const enabled = ele.enabled ? 1 : 0;
            if (ele.enabled)
                numberOfSettings++;
            if (Object.keys(ele).includes('value')) {
                // slider type
                if (typeof ele.value == 'number')
                    userSetting =
                        userSetting +
                            SLIDER_TYPE +
                            SETTING_DELIMITER +
                            enabled +
                            SETTING_DELIMITER +
                            ele.value;
                else {
                    userSetting =
                        userSetting +
                            RANGE_TYPE +
                            SETTING_DELIMITER +
                            enabled +
                            SETTING_DELIMITER +
                            ((_a = ele.value) === null || _a === void 0 ? void 0 : _a.lower) +
                            SETTING_DELIMITER +
                            ((_b = ele.value) === null || _b === void 0 ? void 0 : _b.upper);
                }
            }
            else {
                // boolean type
                userSetting = userSetting + BOOLEAN_TYPE + SETTING_DELIMITER + enabled;
            }
            if (i != setting.length - 1)
                userSetting = userSetting + SETTING_SEPARATOR;
        }
        return numberOfSettings + SETTING_SEPARATOR + userSetting;
    }
    getChannelOrAliasInfo(address) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            try {
                address = (0, helpers_2.validateCAIP)(address)
                    ? address
                    : (0, helpers_2.getFallbackETHCAIPAddress)(this.env, this.account);
                const channelInfo = yield PUSH_CHANNEL.getChannel({
                    channel: address,
                    env: this.env,
                });
                if (channelInfo)
                    return channelInfo;
                // // TODO: Temp fix, do a more concrete fix later
                const API_BASE_URL = (0, helpers_2.getAPIBaseUrls)(this.env);
                const apiEndpoint = `${API_BASE_URL}/v1/alias`;
                const requestUrl = `${apiEndpoint}/${address}/channel`;
                const aliasInfo = yield axios_1.default
                    .get(requestUrl)
                    .then((response) => response.data)
                    .catch((err) => {
                    console.error(`[EPNS-SDK] - API ${requestUrl}: `, err);
                });
                const aliasInfoFromChannel = yield PUSH_CHANNEL.getChannel({
                    channel: aliasInfo.channel,
                    env: this.env,
                });
                if (aliasInfoFromChannel)
                    return aliasInfoFromChannel;
                return null;
            }
            catch (error) {
                return null;
            }
        });
    }
    getAddressFromCaip(caipAddress) {
        return caipAddress === null || caipAddress === void 0 ? void 0 : caipAddress.split(':')[(caipAddress === null || caipAddress === void 0 ? void 0 : caipAddress.split(':').length) - 1];
    }
}
exports.PushNotificationBaseClass = PushNotificationBaseClass;
//# sourceMappingURL=pushNotificationBase.js.map