'use strict';

require('winston').level = 'info';

const Rx = require('rxjs');
const _ = require('lodash');

const { dbUrl } = require('./conf/development');
const db = require('./lib/db/index');
const twitterClient = require('./lib/twitter-service');
const twitterCredentials = require('./conf/twitterCredentials.json');
const tweetService = require('./lib/tweet');
const { logger } = require('./lib/utils');


const log = logger('./index.js')('');
const firstParam = 2;
const KEYWORD = process.env.KEYWORD || process.argv[firstParam];
const MONGO_DB_URL = process.env.MONGO_DB_URL || dbUrl;


const separator = '###########################################';
log('info', `
${ separator }
    KEYWORD for stream: ${ KEYWORD }
${ separator }
`);


const emitterToStream = eventEmmitter => Rx.Observable.fromEvent(eventEmmitter, 'data');
const subscribeToStream = stream => stream.subscribe(
    tweetService.handle,
    err => log('error', err),
    finalMsg => log('info', `
        ${ separator }
        final:
        ${ finalMsg }
        ${ separator }
    `)
);


db.connectTo(MONGO_DB_URL)
    .then(() => twitterClient.createTwitterClient(twitterCredentials))
    .then(twitterClient.getKeywordStream(KEYWORD))
    .then(_.flow(emitterToStream, subscribeToStream));
