# RuntimeError: Click will abort further execution because Python 3 was configured to use ASCII as encoding for the environment. 
# Consult https://click.palletsprojects.com/en/7.x/python3/ for mitigation steps.
from .utils import mysetlocale
mysetlocale()


import logging
logger = logging.getLogger('isitfit')

from .mainManager import MainManager
from .utilizationListener import UtilizationListener
from .optimizerListener import OptimizerListener
import click

from . import isitfit_version



def display_footer():
    logger.info("Generated by isitfit version %s"%isitfit_version)
    logger.info("Utilization is based on CPU only and not yet on memory, disk, network")
    logger.info("For more info about isitfit, check https://isitfit.autofitcloud.com")
    logger.info("")
    logger.info("On a side note: consider following the Global Climate Strike news at https://twitter.com/hashtag/ClimateStrike")
    logger.info("They make a good point.")

# With atexit, this message is being displayed even in case of early return or errors.
# Changing to try/finally in the __main__ below
#import atexit
#atexit.register(display_footer)


@click.command()
@click.option('--debug', is_flag=True)
@click.option('--version', is_flag=True)
@click.option('--optimize', is_flag=True)
@click.option('--n', default=0, help='number of ec2 optimizations to find before stopping. Use 0 for getting all optimizations')
def cli(debug, version, optimize, n):

    if version:
      print('isitfit version %s'%isitfit_version)
      return

    logLevel = logging.DEBUG if debug else logging.INFO
    ch = logging.StreamHandler()
    ch.setLevel(logLevel)
    logger.addHandler(ch)
    logger.setLevel(logLevel)


    #logger.info("Is it fit?")

    logger.info("Initializing...")
    ul = UtilizationListener()
    ol = OptimizerListener(n)
    mm = MainManager()

    # utilization listeners
    if not optimize:
      mm.add_listener('ec2', ul.per_ec2)
      mm.add_listener('all', ul.after_all)
    else:
      mm.add_listener('ec2', ol.per_ec2)
      mm.add_listener('all', ol.after_all)

    # start download data and processing
    logger.info("Fetching history...")
    mm.get_ifi()


if __name__ == '__main__':
  try:
    cli()
  finally:
    display_footer()
