/**
 * log.js
 * Copyright (c) 2000 - 2016 Samsung Electronics Co., Ltd. All rights reserved.
 *
 * Contact:
 * Sungmin Kim <sm.art.kim@samsung.com>
 * Jonghwan Park <iwin100.park@samsung.com>
 * Kitae Kim <kt920.kim@samsung.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Contributors:
 * - S-Core Co., Ltd
**/

var dibs = require('../../../core/dibs.js');
var DError = require('../../../core/exception.js');
var mongodb = require('../../../lib/db-connection.js');

var async = require('async');
var util = require('util');
var uuid = require('node-uuid');

var cursors = {};

exports.route = {
    start: function (req) {
        var logger = dibs.thisServer.logger;
        var id = req.data.Id;
        var type = req.data.Type;

        var collectionName = null;
        if (type === 'JOB') {
            collectionName = 'JOB-' + id;
        }

        dibs.log.info('Request server log stream: ' + id);

        var db = null;
        var collection = null;
        var capped;

        async.series([
            function (cb) {
                mongodb.createMongoDBConnectionPool(function (err, conn) {
                    if (err) {
                        dibs.log.error(err);
                    } else {
                        db = conn;
                        collection = db.collection(collectionName);
                    }
                    cb(err);
                });
            },
            function (cb) {
                collection.isCapped(function (err, res) {
                    capped = res;
                    cb(err);
                });
            },
            function (cb) {
                if (!capped) {
                    db.runCommand({
                        convertToCapped: collectionName,
                        size: 1000000
                    }, function (err1) {
                        return cb(err1);
                    });
                } else {
                    return cb(null);
                }
            },
            function (cb) {
                var key = uuid.v4();

                collection.find({}, { tailable: true, timeout: false }, function (err1, cursor) {
                    if (err1) {
                        dibs.log.error(err1);
                        cb(new DError('LOG002'));
                    } else {
                        cursors[key] = cursor;

                        cursor.on('data', function (data) {
                            req.io.emit('push', { data: data, uuid: key });
                        });

                        cursor.on('error', function (err1) {
                            if (err1) {
                                dibs.log.error(err1);
                                dibs.log.error(util.inspect(err1));
                                req.io.emit('error', util.inspect(err1));
                            }
                        });

                        cursor.on('end', function () {
                            dibs.log.info('Close mongodb client connection!');
                            db.close();
                        });

                    }
                    cb(null);
                });
            }
        ],
        function (err) {
            if (err) {
                dibs.log.error(err);
            }
        });
    },
    disconnect: function (req) {
        var key = req.data.uuid;
        var cursor = cursors[key];

        if (cursor) {
            cursor.close(function (err, results) {
                if (err) {
                    dibs.log.error('Closing cursor failure!');
                    dibs.log.error(err);
                }

                delete cursors[key];
                cursors[key] = null;
            });
        }
    }
};
