//you can change environment parameters if needed
//cgate.env_open('subsystems=mq,replclient');
//you can run p2mqrouter with specified ini file
//cgate.run_p2mqrouter('p2mqrouter.ini');
//or with all parameters explicitly provided
//cgate.run_p2mqrouter(4001, 'user', 'password', 'spectra-t1.moex.com:3001', ['spectra-t1.moex.com:3000', 'spectra-t1.moex.com:3003', 'spectra-t1.moex.com:3004']);
//cgate.run_p2mqrouter(4001, 'user', 'password',  'spectra-t0.moex.com:53000', ['spectra-t0.moex.com:53001', 'spectra-t0.moex.com:53003', 'spectra-t0.moex.com:53004']);

js.include('helper.js');

function getMaxSessId(refdata)
{
    var max_sess_id = 0;
    var session = cgate.tbl_handle(refdata, 'session');

    for (var i = 0; i < cgate.table_size(session); i++)
    {
        var rec = cgate.get_record(session, i);
        var sess_id = rec.sess_id;
        if (max_sess_id < sess_id)
        {
            max_sess_id = sess_id;
        }
    }

    return max_sess_id;
}

function getMarketData(refdata, maxSessId)
{
    var riskOrCollateral = [];
    var md = [];
    var fut_sess_contents = cgate.tbl_handle(refdata, 'fut_sess_contents');

    for (var i = 0; i < cgate.table_size(fut_sess_contents); i++)
    {
        var rec = cgate.get_record(fut_sess_contents, i);
        var sess_id = rec.sess_id;
        if (sess_id < maxSessId)
        {
            continue;
        }

        // выбираем только фьючерсы
        if (0 == (rec.signs & (SIGN_SPOT | SIGN_MULTILEG)))
        {
            // пропускаем так же инструменты не торгующиеся ни днем ни вечером
            if (0 != (rec.signs & (SIGN_PRETRADING | SIGN_DAYTRADING)))
            {
                md.push(rec);
            }
        } // коллатеральные инструменты (позиции по активам)
        else if ((SIGN_SPOT | SIGN_COLLATERAL) == (rec.signs & (SIGN_SPOT | SIGN_COLLATERAL)))
        {
            riskOrCollateral.push(rec.isin_id);
        } // инструменты переноса риска
        else if ((SIGN_MONEY | SIGN_RISK_TRANSFER) == (rec.signs & (SIGN_MULTILEG | SIGN_MONEY | SIGN_RISK_TRANSFER)))
        {
            riskOrCollateral.push(rec.isin_id);
        }
    }

    md.sort(function (a, b) {
        if (a.base_contract_code < b.base_contract_code) {
            return -1;
        }
        else if (b.base_contract_code < a.base_contract_code) {
            return 1;
        }
        else {
            if (a.d_exp_start < b.d_exp_start) {
                return -1;
            }
            else if (b.d_exp_start < a.d_exp_start) {
                return 1;
            }
        }
        return 0;
    })

    return md;
}

var conn = openConnection('p2lrpcq://127.0.0.1:4001;app_name=replspy');
var refDataLsn = openListener(conn, 'p2repl://FORTS_REFDATA_REPL', 'mode=snapshot');

// waiting until listeners get CG_MSG_CLOSE notification with reason = 4(CG_REASON_SNAPSHOT_DONE)
while (!(cgate.is_lsn_snapshot_done(refDataLsn)))
{
    cgate.process();
}

console.log('Listeners ready');

var maxSessId = getMaxSessId(refDataLsn);
console.log('maxSessId = ' + maxSessId);

var md = getMarketData(refDataLsn, maxSessId);

var marketDataFile = fs.open_file('md.csv', 'w');
if (!marketDataFile)
{
    throw new Error('Failed to create market data file');
}

console.log('Writing marketdata file to md.csv');

fs.write(marketDataFile, 'BC;Num;Bid;Ask;Last\n');
if (!fs.is_ok(marketDataFile))
{
    console.log('Error while writing to file. ' + fs.error_string(marketDataFile));
}

var curBC;
var curNum = 0;
for (var i = 0; i < md.length; i++)
{
    if (curBC != md[i].base_contract_code)
    {
        curBC = md[i].base_contract_code;
        curNum = 1;
    }
    else
    {
        ++curNum;
    }
    fs.write(marketDataFile, md[i].base_contract_code + ';' + curNum + ';' + md[i].settlement_price + ';' + md[i].settlement_price + ';' + md[i].settlement_price + '\n');
    if (!fs.is_ok(marketDataFile))
    {
        console.log('Error while writing to file. ' + fs.error_string(marketDataFile));
    }
}

fs.close_file(marketDataFile)

console.log('Reading marketdata file content from md.csv');

//console.log(fs.read_all('md.csv'));

var readMarketDataFile = fs.open_file('md.csv', 'r');
if (!readMarketDataFile)
{
    throw new Error('Failed to open market data file');
}

while (!fs.file_at_end(readMarketDataFile))
{
    console.log(fs.read_line(readMarketDataFile));
};

fs.close_file(readMarketDataFile)

