//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']);

var conn = cgate.conn_open('p2lrpcq://127.0.0.1:4001;app_name=replspy');
//wait for connection status update
if (!cgate.wait_for_conn_opened(conn, 5000)) 
{
    throw new Error('Failed to open the connection');
}

//open some listeners
var inforepl = cgate.lsn_open(conn, 'p2repl://FORTS_INFO_REPL', 'mode=snapshot+online', 'forts_info_repl.yaml');
var refdata = cgate.lsn_open(conn, 'p2repl://FORTS_REFDATA_REPL', 'mode=snapshot+online', 'forts_refdata_repl.yaml');

if (0 == inforepl || 0 == refdata)
{
    throw new Error('Failed to create listener');
}
else if (!cgate.wait_for_lsn_opened(inforepl, 5000) && !cgate.wait_for_lsn_opened(refdata, 5000))
{
    throw new Error('Failed to open listener');
}

// waiting until listeners get CG_MSG_P2REPL_ONLINE notification
while (!(cgate.is_lsn_online(inforepl) && cgate.is_lsn_online(refdata)))
{
    cgate.process();
}

console.log('Listeners ready');
console.log('Printing table names from FORTS_REFDATA_REPL');

var tables = cgate.table_names(refdata)
for (var i = 0; i < tables.length; i++)
{
    console.log(tables[i]);
}

console.log('Printing futures names from fut_sess_contents');
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);
    console.log(rec.isin + ' ' + rec.name);
}

cgate.export_to_csv(cgate.tbl_handle(refdata, 'user'), 'user.csv');

//cgate.lsn_close(conn, futinfo);
//cgate.lsn_close(conn, refdata);

//cgate.conn_close(conn);
