from . import __version__ as VERSION

import json
import logging
import click

from tabulate import tabulate
import datetime, timeago, dateutil.parser

from shipami.core import ShipAMI

logging.basicConfig()
logger = logging.getLogger(__name__)

state_colors = {
    'available': 'green',
    'pending': 'yellow',
    'failed': 'red'
}

def validate_filter(ctx, param, filters):
    validated_filters = []
    for f in filters:
        try:
            k, v = f.split('=')
            validated_filters.append((k, v))
        except ValueError:
            raise click.BadParameter('filter must be in format "key=value"')
    return tuple(validated_filters)

class AliasedGroup(click.Group):
    ALIASES = {
        'ls': 'list',
        'cp': 'copy',
        'rm': 'delete'
    }

    def get_command(self, ctx, cmd_name):
        rv = click.Group.get_command(self, ctx, cmd_name)
        if rv is not None:
            return rv

        if self.ALIASES.get(cmd_name, None):
            return click.Group.get_command(self, ctx, self.ALIASES[cmd_name])
        return None

@click.group(cls=AliasedGroup)
@click.version_option(VERSION)
@click.option('--profile')
@click.option('--region')
@click.option('-v', '--verbose', is_flag=True, default=False)
@click.pass_context
def cli(ctx, profile, region, verbose):
    """CLI tool to manage AWS AMI and Marketplace"""
    if verbose:
        logger.setLevel(logging.DEBUG)
    else:
        logger.setLevel(logging.INFO)
    ctx.obj = ShipAMI(profile, region)


@cli.command()
@click.option('--quiet', '-q', is_flag=True)
@click.option('--all', '-a', is_flag=True)
@click.option('filter_', '--filter', '-f', multiple=True, callback=validate_filter)
@click.option('--color/--no-color', default=True)
@click.pass_obj
def list(shipami, filter_, all, quiet, color):
    headers = ['NAME', 'RELEASE', 'ID', 'OWNER ID', 'STATE', 'CREATED', 'MANAGED', 'COPIED FROM', 'COPIED TO']
    headers_mapping = {
        'NAME': 'Name',
        'RELEASE': 'Release',
        'ID': 'ImageId',
        'OWNER ID': 'OwnerId',
        'STATE': 'State',
        'CREATED': 'CreationDate',
        'MANAGED': 'Managed',
        'COPIED FROM': 'CopiedFrom',
        'COPIED TO': 'CopiedTo'