# #####################################################################################################################
#  Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.                                                 #
#                                                                                                                     #
#  Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance     #
#  with the License. You may obtain a copy of the License at                                                          #
#                                                                                                                     #
#   http://www.apache.org/licenses/LICENSE-2.0                                                                        #
#                                                                                                                     #
#  Unless required by applicable law or agreed to in writing, software distributed under the License is distributed   #
#  on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for  #
#  the specific language governing permissions and limitations under the License.                                     #
# #####################################################################################################################
import logging
from os import getenv
from uuid import uuid4 as uuid

from crhelper import CfnResource

DEFAULT_LENGTH = 32
logger = logging.getLogger(__name__)
helper = CfnResource(log_level=getenv("LOG_LEVEL", "WARNING"))


@helper.create
def generate_name(event, _):
    """
    Generate a physical resource ID limited in length to event['Length']
    :param event: The CloudFormation custom resource event
    :return: PhysicalResourceId
    """
    length = DEFAULT_LENGTH
    try:
        length = int(event.get("Length", DEFAULT_LENGTH))
    except ValueError:
        pass  # use DEFAULT_LENGTH if the length doesn't convert to an int

    unique_id = uuid().hex[:length]
    logger.info(f"generated unique name {unique_id}")
    helper.Data["Id"] = unique_id
    return event.get("PhysicalResourceId", unique_id)


@helper.update
@helper.delete
def no_op(_, __):
    pass  # pragma: no cover


def handler(event, _):
    """
    Handler entrypoint - see generate_name for implementation details
    :param event: The CloudFormation custom resource event
    :return: PhysicalResourceId
    """
    helper(event, _)  # pragma: no cover
