# -*- coding: utf-8 -*-

from lamvery.actions.base import BaseAction

class SetAliasAction(BaseAction):

    def __init__(self, args):
        super(SetAliasAction, self).__init__(args)
        self._alias = args.alias
        if hasattr(args, 'version'):
            self._alias_version = args.version
        else:
            self._alias_version = None

    def action(self):
        self._logger.info('Start alias setting...')
        alias_name = self._get_alias_name()
        version    = self._get_alias_version()
        func_name  = self._config.get_function_name()
        client     = self.get_client()

        if alias_name is not None:
            current_alias = client.get_alias(func_name, alias_name)
            self._print_alias_diff(alias_name, current_alias, version)

            if len(current_alias) > 0:
                client.update_alias(func_name, alias_name, version)
            else:
                client.create_alias(func_name, alias_name, version)
        self._logger.info('Finish alias setting.')

    def _print_alias_diff(self, name, current, version):
        self._logger.warn(
            '[Function - Alias] {name}: {cur} -> {new}'.format(
                name=name, cur=current.get('FunctionVersion'), new=version))

    def _get_alias_name(self):
        if self._alias is not None:
            return self._alias
        return self._config.get_configuration().get('alias')

    def _get_alias_version(self):
        if self._alias_version is None:
            return '$LATEST'
        return self._alias_version
