
function getTradingPairs(baseAsset) {
    return fetch('https://api.binance.com/api/v3/exchangeInfo')
        .then(response => response.json())
        .then(data => {
            const tradingPairs = {}; // Initialize an empty object

            // Filter symbols with the desired base asset and status "TRADING"
            const filteredSymbols = data.symbols.filter(symbol =>                 
                symbol.quoteAsset === baseAsset && symbol.status === 'TRADING'
            );

            // Shuffle the filtered symbols array
            const shuffledSymbols = filteredSymbols.sort(() => 0.5 - Math.random());

            // Take a maximum of 25 symbols
            const selectedSymbols = shuffledSymbols.slice(0, 25);

            selectedSymbols.forEach(symbol => {
                tradingPairs[symbol.symbol] = `${symbol.baseAsset}/${symbol.quoteAsset}|${symbol.quotePrecision}`;
            });

            return tradingPairs; // Return the object of trading pairs
        })
        .catch(error => console.error('Error fetching data:', error));
}

function getTradingPairs2(baseAsset) {
    return fetch('https://api.binance.com/api/v3/exchangeInfo')
        .then(response => response.json())
        .then(data => {
            const tradingPairs = {}; // Initialize an empty object

            // Filter symbols with the desired base asset and status "TRADING"
            const filteredSymbols = data.symbols.filter(symbol =>                 
                symbol.baseAsset === baseAsset && symbol.status === 'TRADING'
            );

            // Shuffle the filtered symbols array
            const shuffledSymbols = filteredSymbols.sort(() => 0.5 - Math.random());

            // Take a maximum of 25 symbols
            const selectedSymbols = shuffledSymbols.slice(0, 25);

            selectedSymbols.forEach(symbol => {
                tradingPairs[symbol.symbol] = `${symbol.baseAsset}/${symbol.quoteAsset}|${symbol.quotePrecision}`;
            });

            return tradingPairs; // Return the object of trading pairs
        })
        .catch(error => console.error('Error fetching data:', error));
}

function getPairInfo(pair) {
    // Create an array of promises to handle asynchronous calls
    const promises = $.map(pair, function(value, key) {
        var dataSetValues = value.split("|");
        var displayValue = dataSetValues[0];
        var decimal = dataSetValues[1]; // Not used in this example

        // Return the promise for getSymbolInfo
        return getSymbolInfo(key).then(info => {
            // console.log(`Key: ${key}, Value: ${value}<br>`);
            // console.log(`Info: Price Change Percent: ${info.priceChangePercent}, Last Price: ${info.lastPrice}<br><br>`);
            var lastPrice = parseFloat(info.lastPrice).toFixed(8); // Round to 8 decimal places
            var priceChangePercent = parseFloat(info.priceChangePercent).toFixed(2); // Round to 2 decimal places
            var color = priceChangePercent < 0 ? 'red' : 'green';

            // Return the HTML for this trading pair
            return `<tr>
                        <td>${displayValue}</td>
                        <td>${lastPrice}</td>
                        <td class="${color}">${priceChangePercent}%</td>
                    </tr>`;
        });
    });

    // Return a promise that resolves when all the individual promises are done
    return Promise.all(promises).then(rows => {
        return rows.join(''); // Join the rows into a single string
    });
}
function getSymbolInfo(symbol) {
    return fetch('https://api.binance.com/api/v3/ticker/24hr?symbol=' + symbol)
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            // Return an object with the relevant information
            const lastPrice = parseFloat(data.lastPrice); // Convert to number
            const priceChangePercent = parseFloat(data.priceChangePercent);
            return {
                priceChangePercent: priceChangePercent,
                lastPrice: lastPrice
            };
        })
        .catch(error => console.error('Error fetching data:', error));
}
function getPairOrderBook(symbol1,pair,decimal, limit) {
    if(symbol1 == 'USDT' || symbol1 == 'USDC'){
        symbol2 = symbol1;
        symbol1 = 'BTC';
    }else{var dataSetValues = pair.split(symbol1);
        var symbol2 = dataSetValues[1];
    }
    populateOrder_heading(pair);
    //////////////////////////
    return fetch('https://api.binance.com/api/v3/depth?symbol=' + pair + '&limit=' + limit)
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            const orderPairs = {
                bids: [],
                asks: []
            }; // Initialize an object to hold bids and asks

            // Store bids in the orderPairs object
            data.bids.forEach(bid => {
                var price= parseFloat(bid[0]); // Price as number
                var quantity= parseFloat(bid[1]) // Quantity as number
                var total = price * quantity;
                var ele = `<td class="red">${price}</td><td>${quantity}</td><td>${total.toFixed(decimal)}</td>`;
                orderPairs.bids.push(ele);
            });
            
            // Store asks in the orderPairs object
            data.asks.forEach(ask => {
                var price= parseFloat(ask[0]); // Price as number
                var quantity= parseFloat(ask[1]) // Quantity as number
                var total = price * quantity;
                var ele = `<td class="green">${price}</td><td>${quantity}</td><td>${total.toFixed(decimal)}</td>`;
                orderPairs.asks.push(ele);
            });

            // console.log(orderPairs);
            
            populateOrder('.bid_order', orderPairs.bids,symbol1,symbol2);
            populateOrder('.ask_order', orderPairs.asks,symbol1,symbol2);
            return orderPairs; // Return the object containing bids and asks
        })
        .catch(error => console.error('Error fetching data:', error));
}
function populateOrder(tableId, rows,symbol1,symbol2) {
    // Clear existing rows
    $('.sym_price').html(`Price(${symbol1})`);
    $('.sym_qnt').html(`Quantity(${symbol1})`);
    $('.sym_amt').html(`Amount(${symbol2})`);
    $(tableId).html('');
    ////////////
    // var order_head = getSymbolInfo(`${symbol1}${symbol2}`);
    getSymbolInfo(`${symbol1}${symbol2}`).then(info => {
        // console.log(`Key: ${key}, Value: ${value}<br>`);
        // console.log(`Info: Price Change Percent: ${info.priceChangePercent}, Last Price: ${info.lastPrice}<br><br>`);
        var lastPrice = parseFloat(info.lastPrice).toFixed(8); // Round to 8 decimal places
        var priceChangePercent = parseFloat(info.priceChangePercent).toFixed(2); // Round to 2 decimal places
        var color = priceChangePercent < 0 ? 'red' : 'green';

        // Return the HTML for this trading pair
        var data =  `<td>
                    <span>Last Price</span>
                    ${lastPrice}
                </td>
                <td></td>
                <td class="${color}">
                    <span>Change</span>
                    ${priceChangePercent}%
                </td>`;
        $(`.order_heading`).html(data);
    });
    // Append new rows
    var ele = '';
    var color = ['red-bg-80','red-bg-60','red-bg-40','red-bg-20','red-bg-10','red-bg-8','red-bg-5','red-bg'];
    if(tableId == '.ask_order'){
        var color = ['green-bg','green-bg-5','green-bg-8','green-bg-10','green-bg-20','green-bg-40','green-bg-60','green-bg-80'];
    }
    for (let i = 0; i < rows.length; i++) {
        // ele = `<tr class="${color[i]}">${rows[i]}</tr>`;
        $(`.${color[i]}`).html(rows[i]);
        // $(tableId).append(ele);
    }
    // $(tableId).html(ele);
}
function populateOrder_heading(pair) {
    ////////////
    getSymbolInfo(pair).then(info => {
        // console.log(`Key: ${key}, Value: ${value}<br>`);
        // console.log(`Info: Price Change Percent: ${info.priceChangePercent}, Last Price: ${info.lastPrice}<br><br>`);
        var lastPrice = parseFloat(info.lastPrice).toFixed(8); // Round to 8 decimal places
        var priceChangePercent = parseFloat(info.priceChangePercent).toFixed(2); // Round to 2 decimal places
        var color = priceChangePercent < 0 ? 'red' : 'green';

        // Return the HTML for this trading pair
        var data =  `<td>
                    <span>Last Price</span>
                    ${lastPrice}
                </td>
                <td></td>
                <td class="${color}">
                    <span>Change</span>
                    ${priceChangePercent}%
                </td>`;
        $(`.order_heading`).html(data);
    });
}