#!/usr/bin/python
# -*- coding: utf8 -*-
# -*- Mode: Python; py-indent-offset: 4 -*-
# pylint: disable=C0103
"""
    Main file of timevortex.timeserieslogger project.

"""

import logging
import logging.config
from timeserieslogger.utils import argument_parser, init_message, verbose_mode
from filestorage.db import FileStorage
from filestorage.config import Config
from messager.utils import RABBIT_MQ_CREDENTIAL_PROBLEM, ERROR, TIMESERIES
from messager.rbmq_messager import RabbitMQMessager, validate_message

# Globals for this file
DEFAULT_CONFIG_FILE = "/opt/timevortex/config.ini"
TOPICS = (TIMESERIES, ERROR)
MISSING_LOG_FILE = "Missing logging file configuration. Process terminated."
MISSING_DATA_FOLDER = "Missing data folder path. Process terminated."
MISSING_RABBITMQ_CREDENTIAL = "Missing RabbitMQ credentials. Process " \
    "terminated."


class TimeSeriesLogger(object):
    """Main class"""

    def __init__(self, rbmq_user, rbmq_pas, rbmq_host, log_conf, data_f, verb):
        """Constructor"""
        self.logger = logging.getLogger("timeserieslogger")
        self.rbmq_username = rbmq_user
        self.rbmq_password = rbmq_pas
        self.rbmq_host = rbmq_host
        self.log_conf = log_conf
        self.data_folder = data_folder
        self.verbose = verbose

    def new_message(self, chan, method, prop, body):  # pylint: disable=W0613
        """Callback call when a new message is received.

            :param chan: Channel message (RabbitMQ filter).
            :type chan: str.

            :param method: Request information
            :type method: dict.

            :param properties: Header of the socket
            :type properties: dict.

            :param body: Message receive on RabbitMQ.
            :type body: str
        """
        message_error, message = validate_message(body)
        if message_error:
            self.file_storage_space.store_error(message_error)
        elif method.routing_key == ERROR:
            self.file_storage_space.insert_error(message)
        elif method.routing_key == TIMESERIES:
            self.file_storage_space.insert_series(message)

    def main(self):
        """
            Main function of this module.
        """
        # Verify parameter and send error and quit if problem
        condition = self.rbmq_username is None
        condition = condition or self.rbmq_password is None
        condition = condition or self.rbmq_host is None
        if condition:
            print(MISSING_RABBITMQ_CREDENTIAL)
            return
        if log_conf is None:
            print(MISSING_LOG_FILE)
            return
        if data_folder is None:
            print(MISSING_DATA_FOLDER)
            return

        # Init logging file
        logging.config.fileConfig(log_conf)
        # Set folder location
        self.file_storage_space = FileStorage(data_folder)
        # Active verbose mode
        verbose_mode(verbose)
        # Initialize messager
        self.messager = RabbitMQMessager(
            self.rbmq_username,
            self.rbmq_password,
            self.rbmq_host)

        if self.messager.is_connected() is False:
            self.messager.send(
                ERROR,
                RABBIT_MQ_CREDENTIAL_PROBLEM % (
                    self.rbmq_username,
                    self.rbmq_password,
                    self.rbmq_host))
            return
        # Init log message
        init_message(log_conf)

        while True:
            self.messager.consume(TOPICS, self.new_message)


if __name__ == '__main__':
    # Retrieve command line arguments
    args = argument_parser()
    verbose = args.verbose
    config_file = args.config_file
    if config_file is None:
        config_file = DEFAULT_CONFIG_FILE
    config = Config(config_file)

    # Retrieve interresting field from config file
    rabbitmq_username = config.get_messager_rabbitmq_username()
    rabbitmq_password = config.get_messager_rabbitmq_password()
    rabbitmq_host = config.get_messager_rabbitmq_host()
    log_conf = config.get_timeserieslogger_log_file()
    data_folder = config.get_filestorage_data_folder()

    # Launch main method
    tsl = TimeSeriesLogger(
        rabbitmq_username,
        rabbitmq_password,
        rabbitmq_host,
        log_conf,
        data_folder,
        verbose)
    tsl.main()
