# --------------------------------------------------------------------------- #
# Importing section
# --------------------------------------------------------------------------- #

import os
import sys
import argparse
import logging
import json

from classes.alerts import SlackClient
from influxdb import InfluxDBClient

from classes.data_manager import DataManager

#  --------------------------------------------------------------------------- #
# Functions
# -----------------------------------------------------------------------------#
def slack_msg():
    slack_client = SlackClient(logger, cfg)
    if bool(dm.files_not_correctly_handled):
        str_err = ''
        for k in dm.files_not_correctly_handled:
            str_err = '%sFailed handling of file %s; Exception: %s\n' % (str_err, k, dm.files_not_correctly_handled[k])
        slack_client.send_alert_message('OZONE FORECASTER - RAW FILES ALARM:\n%s' % str_err, '#ff0000')
    else:
        slack_client.send_alert_message('OZONE FORECASTER - RAW FILES PROPERLY HANDLED', '#00ff00')

# --------------------------------------------------------------------------- #
# Main
# --------------------------------------------------------------------------- #
if __name__ == "__main__":
    # --------------------------------------------------------------------------- #
    # Configuration file
    # --------------------------------------------------------------------------- #
    arg_parser = argparse.ArgumentParser()
    arg_parser.add_argument("-c", help="configuration file")
    arg_parser.add_argument("-l", help="log file (optional, if empty log redirected on stdout)")
    args = arg_parser.parse_args()

    config_file = args.c
    if os.path.isfile(config_file) is False:
        print('\nATTENTION! Unable to open configuration file %s\n' % config_file)
        sys.exit(1)

    cfg = json.loads(open(args.c).read())
    conns_cfg = json.loads(open(cfg['connectionsFile']).read())
    cfg.update(conns_cfg)

    # --------------------------------------------------------------------------- #
    # Set logging object
    # --------------------------------------------------------------------------- #
    if not args.l:
        log_file = None
    else:
        log_file = args.l

    logger = logging.getLogger()
    logging.basicConfig(format='%(asctime)-15s::%(levelname)s::%(funcName)s::%(message)s', level=logging.INFO,
                        filename=log_file)

    # --------------------------------------------------------------------------- #
    # Starting program
    # --------------------------------------------------------------------------- #
    logger.info("Starting program")

    # --------------------------------------------------------------------------- #
    # InfluxDB connection
    # --------------------------------------------------------------------------- #
    logger.info('Connection to InfluxDb server on socket [%s:%s]' % (cfg['influxDB']['host'], cfg['influxDB']['port']))
    try:
        influx_client = InfluxDBClient(host=cfg['influxDB']['host'], port=cfg['influxDB']['port'],
                                       password=cfg['influxDB']['password'], username=cfg['influxDB']['user'],
                                       database=cfg['influxDB']['database'], ssl=cfg['influxDB']['ssl'])
    except Exception as e:
        logger.error('EXCEPTION: %s' % str(e))
        sys.exit(3)
    logger.info('Connection successful')

    dm = DataManager(influx_client, cfg, logger)

    # Download files from the FTP server
    if cfg['ftp']['enabled'] is True:
        logger.info('Download data from FTP server')
        dm.open_ftp_connection()
        dm.download_remote_files()

    # Insert data into InfluxDB
    if cfg['influxDB']['dataImporting'] is True:
        logger.info('Importing in InfluxDB of raw data related to files in %s' % cfg['ftp']['localFolders']['tmp'])
        dm.insert_data()

    # Delete files correctly handled on the FTP server and close the FTP connection
    if cfg['ftp']['enabled'] is True:
        if cfg['ftp']['deleteRemoteFile'] is True:
            logger.info('Delete handled files from FTP server')
            dm.delete_remote_files()

        dm.close_ftp_connection()

    # Slack alert
    if cfg['alerts']['slack']['enabled'] is True:
        slack_msg()

    logger.info("Ending program")

[((20, 19, 20, 43), 'classes.alerts.SlackClient', 'SlackClient', ({(20, 31, 20, 37): 'logger', (20, 39, 20, 42): 'cfg'}, {}), '(logger, cfg)', False, 'from classes.alerts import SlackClient\n'), ((36, 17, 36, 42), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ({}, {}), '()', False, 'import argparse\n'), ((58, 13, 58, 32), 'logging.getLogger', 'logging.getLogger', ({}, {}), '()', False, 'import logging\n'), ((59, 4, 60, 42), 'logging.basicConfig', 'logging.basicConfig', (), '', False, 'import logging\n'), ((80, 9, 80, 48), 'classes.data_manager.DataManager', 'DataManager', ({(80, 21, 80, 34): 'influx_client', (80, 36, 80, 39): 'cfg', (80, 41, 80, 47): 'logger'}, {}), '(influx_client, cfg, logger)', False, 'from classes.data_manager import DataManager\n'), ((42, 7, 42, 34), 'os.path.isfile', 'os.path.isfile', ({(42, 22, 42, 33): 'config_file'}, {}), '(config_file)', False, 'import os\n'), ((44, 8, 44, 19), 'sys.exit', 'sys.exit', ({(44, 17, 44, 18): '(1)'}, {}), '(1)', False, 'import sys\n'), ((72, 24, 74, 104), 'influxdb.InfluxDBClient', 'InfluxDBClient', (), '', False, 'from influxdb import InfluxDBClient\n'), ((77, 8, 77, 19), 'sys.exit', 'sys.exit', ({(77, 17, 77, 18): '(3)'}, {}), '(3)', False, 'import sys\n')]