#!/usr/bin/python
# -*- coding: utf8 -*-
# -*- Mode: Python; py-indent-offset: 4 -*-
# pylint: disable=C0103

""" Main file of TimeVortex project. """

import logging
import logging.config
from timevortex.utils import argument_parser, init_message, verbose_mode
from subprocess import call
from filestorage.config import Config


# Initialize logger
DEFAULT_CONFIG_FILE = "/opt/timevortex/config.ini"

MISSING_LOG_FILE = "Missing logging file configuration. Process terminated."
UNKNOWN_COMMAND = "Unknown command %s. Quit program !"

START_COMMAND = "start"
STOP_COMMAND = "stop"
RESTART_COMMAND = "restart"

LOGGER = logging.getLogger("timevortex")


def start(config):
    """ Start method

        Launch every processes.
    """
    start_currentcost = config.get_activate_timevortex_currentcost()
    start_timeserieslogger = config.get_activate_timevortex_timeserieslogger()

    call(["supervisorctl", "reread"])

    if start_currentcost:
        call(["supervisorctl", "add", "timevortex-currentcost"])
        call(["supervisorctl", "start", "timevortex-currentcost"])

    if start_timeserieslogger:
        call(["supervisorctl", "add", "timevortex-timeserieslogger"])
        call(["supervisorctl", "start", "timevortex-timeserieslogger"])


def stop():
    """ Stop method

        Stop every processes.
    """
    call(["supervisorctl", "stop", "timevortex-currentcost"])
    call(["supervisorctl", "stop", "timevortex-timeserieslogger"])


def restart(config):
    """ Restart method

        Restart every processes.
    """
    stop()
    start(config)


def main():
    """Main method that start timevortex process
    """

    # Parse command line argument and format it into according variable
    args = argument_parser()
    command = args.command
    config_file = args.config_file
    if config_file is None:
        config_file = DEFAULT_CONFIG_FILE
    config = Config(config_file)
    verbose = args.verbose

    log_file = config.get_timevortex_log_file()

    if log_file is None:
        print(MISSING_LOG_FILE)
        return

    logging.config.fileConfig(log_file)
    # Active verbose mode
    verbose_mode(verbose)
    # Init log message
    init_message(log_file)
    # Start/stop program
    if command == START_COMMAND:
        start(config)
    elif command == STOP_COMMAND:
        stop()
    elif command == RESTART_COMMAND:
        restart(config)
    else:
        LOGGER(UNKNOWN_COMMAND % command)


if __name__ == '__main__':
    # Launch main method
    main()
