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

""" Main file of phase.currencost project. """

# Minimal version is to launch phase-currentcost, phase-timeserieslogger
# with according parameter in supervisor and create according variable devices
# and variable in DB
# Phase script should provide method like start, restart, reload, status, stop

import logging
import logging.config
from pymongo import MongoClient
from phase.utils import argument_parser, init_message, verbose_mode
from subprocess import call


# Load DB information
CLIENT = MongoClient('localhost', 27017)
DB = CLIENT.phase
ERRORS_COLLECTION = DB.errors
SERIES_COLLECTION = DB.series
MESSAGES_COLLECTION = DB.messages
DEVICES_COLLECTION = DB.devices
VARIABLES_COLLECTION = DB.variables

# Initialize logger
DEFAULT_LOG_FILE = "/opt/phase/phase.conf"
logging.config.fileConfig(DEFAULT_LOG_FILE)
LOGGER = logging.getLogger("currentcost")


def start():
    """ Start method

        Launch every processes.
    """
    # Define Variable name
    SITE_ID = "liogen_home"
    DEVICE_ID = "main_cc"
    DEVICE_1 = {
        "siteID": SITE_ID,
        "deviceID": DEVICE_ID,
        "brand": "CurrentCost",
        "model": "EnviR 128",
        "params": {
            "ch3": "main_power",
            "ch3_kwh": "main_energy",
            "tmpr": "living_room_temperature"
        }
    }
    VARIABLE_1 = {
        "variableID": "main_power",
        "siteID": SITE_ID,
        "deviceID": DEVICE_ID,
        "label": "Consommation globale de l'appartement en Watts",
        "type": "power",
        "valueType": "N",
        "unit": "W"
    }
    VARIABLE_2 = {
        "variableID": "main_energy",
        "siteID": SITE_ID,
        "deviceID": DEVICE_ID,
        "label": "Consommation globale de l'appartement en kWh",
        "type": "energy",
        "valueType": "N",
        "unit": "kWh"
    }
    VARIABLE_3 = {
        "variableID": "living_room_temperature",
        "siteID": SITE_ID,
        "deviceID": DEVICE_ID,
        "label": "Température du salon",
        "type": "temperature",
        "valueType": "N",
        "unit": "°C"
    }
    # Insert data in DB
    VARIABLES_COLLECTION.update(
        {"variableID": VARIABLE_1["variableID"]},
        VARIABLE_1,
        True)
    VARIABLES_COLLECTION.update(
        {"variableID": VARIABLE_2["variableID"]},
        VARIABLE_2,
        True)
    VARIABLES_COLLECTION.update(
        {"variableID": VARIABLE_3["variableID"]},
        VARIABLE_3,
        True)
    DEVICES_COLLECTION.update(
        {"deviceID": DEVICE_1["deviceID"]},
        DEVICE_1,
        True)

    call(["supervisorctl", "reread"])
    call(["supervisorctl", "add", "phase-currentcost"])
    call(["supervisorctl", "add", "phase-timeserieslogger"])
    call(["supervisorctl", "start", "phase-currentcost"])
    call(["supervisorctl", "start", "phase-timeserieslogger"])


def stop():
    """ Stop method

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


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

    # Parse command line argument and format it into according variable
    args = argument_parser()
    command = args.command
    verbose = args.verbose
    # Active verbose mode
    verbose_mode(verbose)
    # Init log message
    init_message(DEFAULT_LOG_FILE)
    # Start/stop program
    if command == "start":
        start()
    elif command == "stop":
        stop()
    else:
        LOGGER("Unknown command %s. Quit program !" % command)


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