/**
 * log-cleaner.js
 * Copyright (c) 2000 - 2015 Samsung Electronics Co., Ltd. All rights reserved.
 *
 * Contact:
 * DongHee Yang <donghee.yang@samsung.com>
 * Sungmin Kim <sm.art.kim@samsung.com>
 * Jiil Hyoun <jiil.hyoun@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 _ = require('underscore');
var async = require('async');
var mongojs = require('mongojs');
var optimist = require('optimist');
var moment = require('moment');

var argv = optimist.usage('Usage: $0  [--host <Host>] [--port <Port>] [--user <userId>] [--password <password>] <--name <DB Name>> [--remain-days <Remain data days>]')
    .default('host', '127.0.0.1')
    .default('port', '27017')
    .default('remain-days', '7')
    .describe('host', 'DB HOST')
    .describe('port', 'DB PORT')
    .describe('user', 'DB USER')
    .describe('password', 'DB PASSWORD')
    .describe('name', 'DB NAME')
    .describe('remain-days', 'Remove target date of less than the date')
    .argv;

if (!argv.name || argv.help) {
    optimist.showHelp();
    return;
}

var db_host = argv.host;
var db_port = argv.port;
var db_user = argv.user;
var db_password = argv.password;
var db_name = argv.name;
var remain_days = argv['remain-days'];
var server_options = {
    auto_reconnect: true,
    poolSize: 5
};

var today = moment();
var remainDate = today.subtract(remain_days, 'days');
console.log('Remove DB: before ' + remainDate.format('YYYY/MM/DD'));

var db;

async.waterfall([
    function (cb1) {
        console.error('Connect: ' + db_host + ':' + db_port + '/' + db_name);
        db = mongojs(db_host + ':' + db_port + '/' + db_name);
        db.getLastError(function (err) {
            cb1(err);
        });
    },
    function (cb1) {
        db.getCollectionNames(function (err, res) {
            cb1(err, res);
        });
    },
    function (collections, cb1) {
        async.eachSeries(collections,
            function (name, cb2) {
                if (name === 'collectionICareAbout' || name === 'system.indexes' || name === 'system.users') {
                    console.log('SKIP: ' + name);
                    cb2(null);
                    return;
                }
                var collection = db.collection(name);
                if (!collection) {
                    console.log('SKIP: ' + name);
                    cb2(null);
                    return;
                }

                if (name.indexOf('JOB') > -1) {
                    collection.findOne({}, {}, function (err, res) {
                        if (err) {
                            cb2(err);
                            return;
                        }

                        var dropFlag = false;
                        if (!res || !res.timestamp) {
                            dropFlag = true;
                        } else {
                            var jobDate = moment(res.timestamp);
                            if (jobDate.format('YYYYMMDD') <= remainDate.format('YYYYMMDD')) {
                                dropFlag = true;
                            }
                        }

                        if (dropFlag) {
                            console.log('DROP LOG: ' + name);
                            collection.drop(function (err) {
                                cb2(err);
                            });
                        } else {
                            cb2(null);
                        }
                    });
                } else {
                    collection.remove({
                        timestamp: {
                            $lt: remainDate.toDate()
                        }
                    }, function (err, res) {
                        console.log('DELETE LOG: ' + name);
                        cb2(null);
                    });
                }
            },
            function (err) {
                cb1(err);
            });
    }
], function (err) {
    console.log('Finish');
    db.close();
    if (err) {
        console.error(err);
    }
});

