# 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')

import click

from . import isitfit_version

def display_footer():
    logger.info("Generated by isitfit version %s"%isitfit_version)
    logger.info("For more info about isitfit, check https://isitfit.autofitcloud.com ⛅")
    logger.info("Also, consider following the Global Climate Strike news at https://twitter.com/hashtag/ClimateStrike 🌎")

# 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.group(invoke_without_command=True)
@click.option('--debug', is_flag=True, help='Display more details to help with debugging')
@click.option('--version', is_flag=True, help='Show the installed version')
@click.option('--optimize', is_flag=True, help='Generate recommendations of optimal EC2 sizes')
@click.option('--n', default=0, help='number of underused ec2 optimizations to find before stopping. Skip to get all optimizations')
@click.option('--filter-tags', default=None, help='filter instances for only those carrying this value in the tag name or value')
@click.pass_context
def cli(ctx, debug, version, optimize, n, filter_tags):
    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)

    # do not continue with the remaining code here
    # if a command is invoked, eg `isitfit tags`
    ctx.ensure_object(dict)
    if ctx.invoked_subcommand is not None:
      return

    #logger.info("Is it fit?")
    try:
      logger.info("Initializing...")

      # moved these imports from outside the function to inside it so that `isitfit --version` wouldn't take 5 seconds due to the loading
      from .mainManager import MainManager
      from .utilizationListener import UtilizationListener
      from .optimizerListener import OptimizerListener
      from .datadogManager import DatadogManager

      ul = UtilizationListener()
      ol = OptimizerListener(n)
      ddg = DatadogManager()
      mm = MainManager(ddg, filter_tags)

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


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

    finally:
      display_footer()

#-----------------------

@cli.group(help="Explore EC2 tags", invoke_without_command=False)
@click.pass_context
def tags(ctx):
  from .tagsListener import TagsListener
  tl = TagsListener()
  tl.fetch()
  ctx.obj['tl'] = tl

@tags.command(help="Dump EC2 tags in tabular form into a csv file")
@click.pass_context
def dump(ctx):
  ctx.obj['tl'].dump()
  display_footer()

#-----------------------

if __name__ == '__main__':
  cli()
