"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) {
                if (!('_signTypedData' in signer) && !('signTypedData' in signer)) {
                    throw new Error('Unsupported signer type');
                }
                else if ('_signTypedData' in signer) {
                    derivedAccount = yield (0, helpers_1.getAccountAddress)({
                        account: null,
                        signer: signer,
                    });
                    if (signer === null || signer === void 0 ? void 0 : signer.provider) {
                        coreContract = new ethers_1.ethers.Contract(config.CORE_CONFIG[env].EPNS_CORE_CONTRACT, config.ABIS.CORE, signer);
                    }
                }
                else if ('signTypedData' in signer) {
                    derivedAccount = yield (0, helpers_1.getAccountAddress)({
                        account: null,
                        signer: 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,
                    });
                }
            }
            // 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) {
        var _a;
        let contract;
        if (!('_signTypedData' in this.signer) &&
            !('signTypedData' in this.signer)) {
            throw new Error('Unsupported signer type');
        }
        else if ('_signTypedData' in this.signer) {
            if (!((_a = this.signer) === null || _a === void 0 ? void 0 : _a.provider)) {
                throw new Error('Provider is required');
            }
            contract = new ethers_1.ethers.Contract(contractAddress, contractABI, this.signer);
        }
        else if ('signTypedData' in 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 {
            throw new Error('Unsupported signer type');
        }
        return contract;
    }
    fetchBalance(contract, userAddress) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            let balance;
            try {
                if ('_signTypedData' in this.signer) {
                    balance = yield contract['balanceOf'](userAddress);
                }
                else if ('signTypedData' in this.signer) {
                    const balanceInBigInt = yield contract.read.balanceOf({
                        args: [userAddress],
                    });
                    balance = ethers_1.ethers.BigNumber.from(balanceInBigInt);
                }
                else {
                    throw new Error('Unsupported signer');
                }
                return balance;
            }
            catch (error) {
                console.log(error);
                throw new Error(JSON.stringify(error));
            }
        });
    }
    fetchAllownace(contract, userAddress, spenderAddress) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            let allowance;
            try {
                if ('_signTypedData' in this.signer) {
                    allowance = yield contract['allowance'](userAddress, spenderAddress);
                }
                else if ('signTypedData' in this.signer) {
                    const allowanceInBigInt = yield contract.read.allowance({
                        args: [userAddress, spenderAddress],
                    });
                    allowance = ethers_1.ethers.BigNumber.from(allowanceInBigInt);
                }
                else {
                    throw new Error('Unsupported signer');
                }
                return allowance;
            }
            catch (error) {
                throw new Error(JSON.stringify(error));
            }
        });
    }
    fetchUpdateCounter(contract, userAddress) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            let count;
            try {
                if ('_signTypedData' in this.signer) {
                    count = yield contract['channelUpdateCounter'](userAddress);
                }
                else if ('signTypedData' in this.signer) {
                    const countInBigInt = yield contract.read.channelUpdateCounter({
                        args: [userAddress],
                    });
                    count = ethers_1.ethers.BigNumber.from(countInBigInt);
                }
                else {
                    throw new Error('Unsupported signer');
                }
                // add one and return the count
                return count.add(ethers_1.ethers.BigNumber.from(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 ('_signTypedData' in 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));
                    // console.log(approvalTrx.hash)
                }
                else if ('signTypedData' in this.signer) {
                    if (!contract.write) {
                        throw new Error('viem signer is not provided');
                    }
                    const approvalTrxPromise = contract.write.approve({
                        args: [spenderAddress, amount],
                    });
                    const approvalTrxRes = yield approvalTrxPromise;
                    // console.log(approvalTrxRes);
                }
                else {
                    throw new Error('Unsupported signer');
                }
                return true;
            }
            catch (error) {
                console.log(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 || !this.signer.provider) {
                    throw new Error('ethers provider/signer is not provided');
                }
                if ('_signTypedData' in 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 ('signTypedData' in this.signer) {
                    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 || !this.signer.provider) {
                    throw new Error('ethers provider/signer is not provided');
                }
                if ('_signTypedData' in 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 ('signTypedData' in this.signer) {
                    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 {
                let verifyTrxRes;
                if ('_signTypedData' in this.signer) {
                    if (!this.signer || !this.signer.provider) {
                        throw new Error('ethers provider/signer 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 ('signTypedData' in this.signer) {
                    if (!contract.write) {
                        throw new Error('viem signer is not provided');
                    }
                    const verifyTrxPromise = contract.write.verify({
                        args: [channelToBeVerified],
                    });
                    verifyTrxRes = yield verifyTrxPromise;
                }
                else {
                    throw new Error('Unsupported signer');
                }
                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 {
                let createSettingsRes;
                if ('_signTypedData' in this.signer) {
                    if (!this.signer || !this.signer.provider) {
                        throw new Error('ethers provider/signer 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 ('signTypedData' in this.signer) {
                    if (!contract.write) {
                        throw new Error('viem signer is not provided');
                    }
                    const createSettingsTrxPromise = contract.write.createChannelSettings({
                        args: [numberOfSettings, settings, description, fees],
                    });
                    createSettingsRes = yield createSettingsTrxPromise;
                }
                else {
                    throw new Error('Unsupported signer');
                }
                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 {
                let addDelegateRes;
                if ('_signTypedData' in this.signer) {
                    if (!this.signer || !this.signer.provider) {
                        throw new Error('ethers provider/signer 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 ('signTypedData' in this.signer) {
                    if (!contract.write) {
                        throw new Error('viem signer is not provided');
                    }
                    const addDelegateTrxPromise = contract.write.addDelegate({
                        args: [delegatee],
                    });
                    addDelegateRes = yield addDelegateTrxPromise;
                }
                else {
                    throw new Error('Unsupported signer');
                }
                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 {
                let removeDelegateRes;
                if ('_signTypedData' in this.signer) {
                    if (!this.signer || !this.signer.provider) {
                        throw new Error('ethers provider/signer 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 ('signTypedData' in this.signer) {
                    if (!contract.write) {
                        throw new Error('viem signer is not provided');
                    }
                    const removeDelegateTrxPromise = contract.write.removeDelegate({
                        args: [delegatee],
                    });
                    removeDelegateRes = yield removeDelegateTrxPromise;
                }
                else {
                    throw new Error('Unsupported signer');
                }
                return removeDelegateRes;
            }
            catch (error) {
                throw new Error(error.message);
            }
        });
    }
    getChianId(signer) {
        var _a;
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            let chainId;
            const isProviderExists = yield this.checkProvider(signer);
            if (!isProviderExists) {
                throw new Error('Provider doesnt exists');
            }
            if ('_signTypedData' in signer) {
                const chainDetails = yield ((_a = signer === null || signer === void 0 ? void 0 : signer.provider) === null || _a === void 0 ? void 0 : _a.getNetwork());
                chainId = chainDetails === null || chainDetails === void 0 ? void 0 : chainDetails.chainId;
            }
            else if ('signTypedData' in signer) {
                chainId = yield signer.getChainId();
            }
            return chainId;
        });
    }
    checkProvider(signer) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            let res = false;
            if ('_signTypedData' in signer) {
                res = signer && (signer === null || signer === void 0 ? void 0 : signer.provider) ? true : false;
            }
            else if ('signTypedData' in signer) {
                const chainId = yield signer.getChainId();
                res = !!chainId;
            }
            return res;
        });
    }
    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;
            }
        });
    }
}
exports.PushNotificationBaseClass = PushNotificationBaseClass;
//# sourceMappingURL=pushNotificationBase.js.map