const WebSocket = require('ws');
const axios = require('axios');
const delay = 150000;
const qs = require('qs');
const fs = require('fs');
const { base64encode } = require('nodejs-base64');
let apiFile = require('./api');

// counter for error and close max to 3
var error_i = 0;
var close_i = 0;

marginAccount = [];

var token = apiFile.generateToken();

function sendNotification(msg) {
    const TOKEN = 'bot5443591188:AAFacX64-rh55iiMoisP2IN-ZjrbmeYdopw';
    const telegramIds = [1702588280];

    for (let i = 0; i < telegramIds.length; i++) {
        axios.get('https://api.telegram.org/' + TOKEN + '/sendMessage?chat_id=' + telegramIds[i] + '&text=' + msg)
            .then(res => {
                console.log('Notification Sent Successfully');
            })
            .catch(error => {
                console.error(error);
                sendNotification('Telegram Error');
            });
    }
}

function connectWebsocket(token) {
    const url = 'wss://demo.sevenstarfx.com:6234/live?auth=' + token;

    const ws = new WebSocket(url);

    const ping = () => {
        heartbeat(ws, delay)
    }

    const heartbeat = (ws, delay) => {
        clearTimeout(ws.pingTimeout)

        ws.pingTimeout = setTimeout(() => {
            ws.terminate()
        }, delay)
    }

    ws.on('ping', ping)
        .on('open', () => {

            sendNotification('Connection Opened!');

            ws.send(JSON.stringify({ protocol: 'json', version: 1 }) + '\u001e');

            // Subscribe MarginEvent
            ws.send(JSON.stringify({ target: "tradesSubscription", arguments: [true], type: 1 }) + '\u001e');

            sendNotification('Trade Subscription Started');
        })
        .on('message', (data) => {
            data = data.toString().replace('\u001e', '');
            data = data.toString().replace('▲', '');
            data = JSON.parse(data.replace('\u001e', ''));

            if (data.type == 1 || data.type == '1') {
                data = data.arguments[0];

                // Stop Out Trade Code Start
                if (data.trade.login == '147880487') {
                    const accountIds = [147880488, 147880489, 147880490, 147880491, 147880492, 147880493, 147880494, 147880495, 147880496, 147880497];

                    for (let i = 0; i < accountIds.length; i++) {

                        var request = { login: accountIds[i], operation: data.trade.cmd, symbol: data.trade.symbol, volume: (data.trade.volume / 100), price: data.trade.openPrice, stopLoss: data.trade.sl, takeProfit: data.trade.tp, comment: data.trade.order };

                        const newurl = 'https://demo.sevenstarfx.com:6234/trades';
                        const options = {
                            method: 'POST',
                            headers: { 'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json' },
                            data: request,
                            url: 'https://demo.sevenstarfx.com:6234/trades',
                        };

                        axios(options)
                            .then((response) => {
                                if (response) {
                                    console.log(response);
                                }
                            }, (error) => {
                                console.log(error);
                            });
                    }
                }
                // Stop Out Trade COde End
            }
            ping();
        })
        .on('error', (error) => {
            sendNotification('Error : ' + error);
            if (error_i < 3) {
                connectWebsocket();
                error_i++;
            } else {
                sendNotification('Stopout Trade Retry 3 Times Compleded!');
            }
        })
        .on('close', () => {
            sendNotification('Connection Closed');
            clearTimeout(ws.pingTimeout);

            // reconnect websocket
            if (close_i < 3) {
                connectWebsocket();
                close_i++;
            } else {
                sendNotification('Stopout Trade Retry 3 Times Compleded!');
            }
        })
}



connectWebsocket(token);