#!/usr/bin/env python
from mistansible.helpers import authenticate
from ansible.module_utils.basic import *

DOCUMENTATION = '''
module: mist_locations
short_description: Lists all available locations/regions for a cloud
description:
  - Returns a list of all available locations/regions for a given cloud
  - I(mist_email) and I(mist_password) can be skipped if I(~/.mist) config file is present.
  - See documentation for config file U(http://mistclient.readthedocs.org/en/latest/cmd/cmd.html)
options:
  mist_email:
    description:
      - Email to login to the mist.io service
    required: false
  mist_password:
    description:
      - Password to login to the mist.io service
    required: false
  mist_uri:
    default: https://mist.io
    description:
      - Url of the mist.io service. By default https://mist.io. But if you have a custom installation of mist.io you can provide the url here
    required: false
  cloud:
    description:
      - Can be either cloud's id or name
    required: true
author: "Mist.io Inc"
version_added: "1.7.1"

'''

EXAMPLES = '''
- name: List locations for a cloud
  mist_locations:
    mist_email: your@email.com
    mist_password: yourpassword
    cloud: DigitalOcean
  register: locations

'''


def list_locations(module, client):
    cloud_name = module.params.get('cloud')
    clouds = client.clouds(search=cloud_name)
    if not clouds:
        module.fail_json(msg="You have to provide a valid cloud id or title")
    cloud = clouds[0]

    locations = cloud.locations
    return [{'name': location['name'], 'id': location['id']} for location in locations]


def main():
    module = AnsibleModule(
        argument_spec=dict(
            mist_uri=dict(default='https://mist.io', type='str'),
            mist_email=dict(required=False, type='str'),
            mist_password=dict(required=False, type='str'),
            cloud=dict(required=True, type='str'),
        )
    )

    client = authenticate(module)

    locations = list_locations(module, client)

    module.exit_json(changed=False, locations=locations)


main()