#!/usr/bin/python
#
# Copyright (C) 2019 Junyi Yi (@JunyiYi)
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)

# ----------------------------------------------------------------------------
#
#     ***     AUTO GENERATED CODE    ***    AUTO GENERATED CODE     ***
#
# ----------------------------------------------------------------------------
#
#     This file is automatically generated by Magic Modules and manual
#     changes will be clobbered when the file is regenerated.
#
#
# ----------------------------------------------------------------------------

from __future__ import absolute_import, division, print_function
__metaclass__ = type

DOCUMENTATION = '''
---
module: azure_rm_batchaccount
version_added: "0.1.2"
short_description: Manages a Batch Account on Azure
description:
    - Create, update and delete instance of Azure Batch Account.

options:
    resource_group:
        description:
            - The name of the resource group in which to create the Batch Account.
        required: true
        type: str
    name:
        description:
            - The name of the Batch Account.
        required: true
        type: str
    location:
        description:
            - Specifies the supported Azure location where the resource exists.
        type: str
    auto_storage_account:
        description:
            - Existing storage account with which to associate the Batch Account.
            - It can be the storage account name which is in the same resource group.
            - It can be the storage account ID. Fox example "/subscriptions/{subscription_id}/resourceGroups/
              {resource_group}/providers/Microsoft.Storage/storageAccounts/{name}".
            - It can be a dict which contains I(name) and I(resource_group) of the storage account.
        type: raw
    key_vault:
        description:
            - Existing key vault with which to associate the Batch Account.
            - It can be the key vault name which is in the same resource group.
            - It can be the key vault ID. For example "/subscriptions/{subscription_id}/resourceGroups/
              {resource_group}/providers/Microsoft.KeyVault/vaults/{name}".
            - It can be a dict which contains I(name) and I(resource_group) of the key vault.
        type: raw
    pool_allocation_mode:
        description:
            - The pool acclocation mode of the Batch Account.
        default: batch_service
        choices:
            - batch_service
            - user_subscription
        type: str
    state:
        description:
            - Assert the state of the Batch Account.
            - Use C(present) to create or update a Batch Account and C(absent) to delete it.
        default: present
        type: str
        choices:
            - present
            - absent

extends_documentation_fragment:
    - azure.azcollection.azure
    - azure.azcollection.azure_tags
    - azure.azcollection.azure_identity_single

author:
    - Junyi Yi (@JunyiYi)
'''

EXAMPLES = '''
- name: Create Batch Account
  azure_rm_batchaccount:
    resource_group: MyResGroup
    name: mybatchaccount
    location: eastus
    auto_storage_account:
      name: mystorageaccountname
    pool_allocation_mode: batch_service
'''

RETURN = '''
id:
    description:
        - The ID of the Batch account.
    returned: always
    type: str
    sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Batch/batchAccounts/sampleacct"
account_endpoint:
    description:
        - The account endpoint used to interact with the Batch service.
    returned: always
    type: str
    sample: sampleacct.westus.batch.azure.com
'''

from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common_ext import AzureRMModuleBaseExt
from ansible.module_utils.common.dict_transformations import _snake_to_camel

try:
    from azure.core.polling import LROPoller
    from azure.core.exceptions import ResourceNotFoundError
    from azure.mgmt.batch.models import BatchAccountIdentity, UserAssignedIdentities
except ImportError:
    # This is handled in azure_rm_common
    pass


class Actions:
    NoAction, Create, Update, Delete = range(4)


class AzureRMBatchAccount(AzureRMModuleBaseExt):
    """Configuration class for an Azure RM Batch Account resource"""

    def __init__(self):
        self.module_arg_spec = dict(
            resource_group=dict(
                required=True,
                type='str'
            ),
            name=dict(
                required=True,
                type='str'
            ),
            location=dict(
                type='str'
            ),
            auto_storage_account=dict(
                type='raw'
            ),
            key_vault=dict(
                type='raw',
                no_log=True
            ),
            pool_allocation_mode=dict(
                default='batch_service',
                type='str',
                choices=['batch_service', 'user_subscription']
            ),
            identity=dict(
                type="dict",
                options=self.managed_identity_single_spec
            ),
            state=dict(
                type='str',
                default='present',
                choices=['present', 'absent']
            )
        )

        self.resource_group = None
        self.name = None
        self.batch_account = dict()

        self.results = dict(changed=False)
        self.state = None
        self.to_do = Actions.NoAction
        self._managed_identity = None
        self.identity = None

        super(AzureRMBatchAccount, self).__init__(derived_arg_spec=self.module_arg_spec,
                                                  supports_check_mode=True,
                                                  supports_tags=True)

    @property
    def managed_identity(self):
        if not self._managed_identity:
            self._managed_identity = {
                "identity": BatchAccountIdentity,
                "user_assigned": UserAssignedIdentities,
            }
        return self._managed_identity

    def exec_module(self, **kwargs):
        """Main module execution method"""

        for key in list(self.module_arg_spec.keys()) + ['tags']:
            if hasattr(self, key):
                setattr(self, key, kwargs[key])
            elif kwargs[key] is not None:
                self.batch_account[key] = kwargs[key]

        resource_group = self.get_resource_group(self.resource_group)
        if self.batch_account.get('location') is None:
            self.batch_account['location'] = resource_group.location
        if self.batch_account.get('auto_storage_account') is not None:
            self.batch_account['auto_storage'] = {
                'storage_account_id': self.normalize_resource_id(
                    self.batch_account.pop('auto_storage_account'),
                    '/subscriptions/{subscription_id}/resourceGroups/{resource_group}/providers/Microsoft.Storage/storageAccounts/{name}')
            }
        if self.batch_account.get('key_vault') is not None:
            id = self.normalize_resource_id(
                self.batch_account.pop('key_vault'),
                '/subscriptions/{subscription_id}/resourceGroups/{resource_group}/providers/Microsoft.KeyVault/vaults/{name}')
            url = 'https://' + id.split('/').pop() + '.vault.azure.net/'
            self.batch_account['key_vault_reference'] = {
                'id': id,
                'url': url
            }
        self.batch_account['pool_allocation_mode'] = _snake_to_camel(self.batch_account['pool_allocation_mode'], True)

        response = None

        old_response = self.get_batchaccount()
        curr_identity = old_response["identity"] if old_response else None

        update_identity = False
        if self.identity:
            update_identity, identity_result = self.update_single_managed_identity(curr_identity=curr_identity, new_identity=self.identity)
            self.batch_account["identity"] = identity_result.as_dict()

        if not old_response:
            self.log("Batch Account instance doesn't exist")
            if self.state == 'absent':
                self.log("Old instance didn't exist")
            else:
                self.to_do = Actions.Create
        else:
            self.log("Batch Account instance already exists")
            if self.state == 'absent':
                self.to_do = Actions.Delete
            elif self.state == 'present':
                self.results['old'] = old_response
                self.results['new'] = self.batch_account

                update_tags, self.tags = self.update_tags(old_response['tags'])

                if self.batch_account.get('auto_storage_account') is not None:
                    if old_response['auto_storage']['storage_account_id'] != self.batch_account['auto_storage']['storage_account_id']:
                        self.to_do = Actions.Update
                if update_tags or update_identity:
                    self.to_do = Actions.Update

        if (self.to_do == Actions.Create) or (self.to_do == Actions.Update):
            self.log("Need to Create / Update the Batch Account instance")

            self.results['changed'] = True
            if self.check_mode:
                return self.results

            response = self.create_update_batchaccount()

            self.log("Creation / Update done")
        elif self.to_do == Actions.Delete:
            self.log("Batch Account instance deleted")
            self.results['changed'] = True

            if self.check_mode:
                return self.results

            self.delete_batchaccount()
        else:
            self.log("Batch Account instance unchanged")
            self.results['changed'] = False
            response = old_response

        if self.state == 'present':
            self.results.update({
                'id': response.get('id', None),
                'account_endpoint': response.get('account_endpoint', None),
                'new': response
            })
        return self.results

    def create_update_batchaccount(self):
        '''
        Creates or updates Batch Account with the specified configuration.

        :return: deserialized Batch Account instance state dictionary
        '''
        self.log("Creating / Updating the Batch Account instance {0}".format(self.name))

        try:
            if self.to_do == Actions.Create:
                response = self.batch_account_client.batch_account.begin_create(resource_group_name=self.resource_group,
                                                                                account_name=self.name,
                                                                                parameters=self.batch_account)
            else:
                response = self.batch_account_client.batch_account.update(resource_group_name=self.resource_group,
                                                                          account_name=self.name,
                                                                          parameters=dict(tags=self.tags,
                                                                                          auto_storage=self.batch_account.get('auto_storage'),
                                                                                          identity=self.batch_account.get('identity')))
            if isinstance(response, LROPoller):
                response = self.get_poller_result(response)
        except Exception as exc:
            self.log('Error attempting to create the Batch Account instance.')
            self.fail("Error creating the Batch Account instance: {0}".format(str(exc)))
        return response.as_dict()

    def delete_batchaccount(self):
        '''
        Deletes specified Batch Account instance in the specified subscription and resource group.

        :return: True
        '''
        self.log("Deleting the Batch Account instance {0}".format(self.name))
        try:
            response = self.batch_account_client.batch_account.begin_delete(resource_group_name=self.resource_group,
                                                                            account_name=self.name)
        except Exception as e:
            self.log('Error attempting to delete the Batch Account instance.')
            self.fail("Error deleting the Batch Account instance: {0}".format(str(e)))

        if isinstance(response, LROPoller):
            response = self.get_poller_result(response)
        return True

    def get_batchaccount(self):
        '''
        Gets the properties of the specified Batch Account
        :return: deserialized Batch Account instance state dictionary
        '''
        self.log("Checking if the Batch Account instance {0} is present".format(self.name))
        found = False
        try:
            response = self.batch_account_client.batch_account.get(resource_group_name=self.resource_group,
                                                                   account_name=self.name)
            found = True
            self.log("Response : {0}".format(response))
            self.log("Batch Account instance : {0} found".format(response.name))
        except ResourceNotFoundError as e:
            self.log('Did not find the Batch Account instance. Exception as {0}'.format(e))
        if found is True:
            return self.format_item(response.as_dict())
        return False

    def format_item(self, item):
        result = {
            'id': item['id'],
            'name': item['name'],
            'type': item['type'],
            'location': item['location'],
            'account_endpoint': item['account_endpoint'],
            'provisioning_state': item['provisioning_state'],
            'pool_allocation_mode': item['pool_allocation_mode'],
            'auto_storage': item['auto_storage'],
            'dedicated_core_quota': item['dedicated_core_quota'],
            'low_priority_core_quota': item['low_priority_core_quota'],
            'pool_quota': item['pool_quota'],
            'active_job_and_job_schedule_quota': item['active_job_and_job_schedule_quota'],
            'tags': item.get('tags'),
            'identity': item.get('identity')
        }
        return result


def main():
    """Main execution"""
    AzureRMBatchAccount()


if __name__ == '__main__':
    main()
