"""AWS resource tag operations."""

import boto3

from .arnparse import arnparse
from .handlers import IAMHandler, TaggingAPIHandler


def get_tags(arns, session=None):
    """Get tags for AWS resources."""
    session = session or boto3.Session()
    handlers = dispatch(arns)
    results = {}
    for handler, handler_arns in handlers.items():
        r = handler.get_tags(session, handler_arns)
        results.update(r)
    return results


def set_tags(arns, tags, session=None):
    """Set tags on AWS resources."""
    session = session or boto3.Session()
    handlers = dispatch(arns)
    results = {}
    for handler, handler_arns in handlers.items():
        r = handler.set_tags(session, handler_arns, tags)
        results.update(r)
    return results


def dispatch(arns):
    """Group ARNs by handler."""
    handler_to_arns = {}
    for arn in arns:
        arn_data = arnparse(arn)

        if arn_data.service == "iam":
            handler = IAMHandler
        else:
            handler = TaggingAPIHandler

        if handler not in handler_to_arns:
            handler_to_arns[handler] = []
        handler_to_arns[handler].append(arn)
    return handler_to_arns
