#!/usr/bin/env  python
# -*- coding: utf-8 -*-

# Copyright (C) 2012, Gustavo Duarte
# Copyright (C) 2013, Miguel González
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import argparse
import logging
import logging.handlers
import sys
import os

from stats_consolidation.db import DB_Stats
from stats_consolidation.consolidation import Consolidation
from stats_consolidation.config import Config


parser = argparse.ArgumentParser()
parser.add_argument('--config_file', required=False)

args = parser.parse_args()


_LOG_FORMAT = '[%(asctime)s]-%(levelname)s-\'%(filename)s\': %(message)s'
_LOG_LEVEL = {'debug': logging.DEBUG,
            'info': logging.INFO,
            'warning': logging.WARNING,
            'error': logging.ERROR,
            'critical': logging.CRITICAL}

log = None


def main():
    if (args.config_file == None):
        config_file = "/etc/stats-consolidation.conf"
    else:
        config_file = args.config_file

    config = Config(config_file)

    LOG_FILENAME = os.path.join(config.log_path, 'stats-consolidation.log')
    # Add the log message handler to the logger
    handler = logging.handlers.RotatingFileHandler(LOG_FILENAME, maxBytes=10000000, backupCount=5)
    handler.setFormatter(logging.Formatter(fmt=_LOG_FORMAT))
    handler.setLevel(_LOG_LEVEL[config.log_level])

    log = logging.getLogger("stats-consolidation")
    log.setLevel(_LOG_LEVEL[config.log_level])
    log.addHandler(handler)

    log.info('**************************************')
    log.info('       Starting consolidation         ')
    log.info('**************************************')

    try:
        db = DB_Stats(config.db_name, config.db_user, config.db_pass, config.db_dialect)
        db.create()
    except Exception as e:
        log.warning('Creating DB: %s', str(e))
        log.critical('Connecting: %s', e)
        msg = 'Critical error trying to connect database:\n {error}\n'
        error = str(e)
        sys.stderr.write(msg.format(error=error))
        sys.exit(1)

    try:
        con = Consolidation(config.rrd_path, db)
        con.process_rrds()
        db.close()

        log.info('**************************************')
        log.info('       Finish consolidation           ')
        log.info('**************************************')
    except Exception as e:
        log.warning('Processing rrd file: %s', str(e))


if __name__ == '__main__':
    main()
