#!/usr/bin/env python
import os

import ConfigParser

from ansible.module_utils.basic import *

from mist.client import MistClient


DOCUMENTATION = '''
module: mist_images
short_description: Lists all available OS images for a backend
description:
  - Returns a list of all available OS images that the given backend supports.
  - I(mist_email) and I(mist_password) can be skipped if I(~/.mist) config file is present.
  - See mist.client documentation for config file U(http://mistclient.readthedocs.org/en/latest/cmd/cmd.html).
requirements:
  - mist.client
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
  backend:
    description:
      - Can be either backend's id or name
    required: true
  search:
    description:
      - If not provided will return a list with default OS Images for the given backend
      - If I(all) is provided, will return ALL available OS images
      - If I(other search term) then it will search for specific images
    required: true
author: "Chris Loukas <commixon@gmail.com>"
version_added: "1.7.1"

'''

EXAMPLES = '''
- name: List default images for NephoScale backend
  mist_images:
    mist_email: your@email.com
    mist_password: yourpassword
    backend: NephoScale
  register: images

- name: Search for gentoo images in backend with id i984JHdkjhKj
  mist_images:
    mist_email: your@email.com
    mist_password: yourpassword
    backend: i984JHdkjhKj
    search: gentoo
  register: images
'''


def authenticate(module):
    home_path = os.getenv("HOME")
    config_path = os.path.join(home_path, ".mist")
    config = ConfigParser.ConfigParser()

    mist_uri = module.params.get('mist_uri')
    mist_email = module.params.get('mist_email')
    mist_password = module.params.get('mist_password')


    # Set default mist uri
    config.add_section("mist.io")
    config.set("mist.io", "mist_uri", "https://mist.io")

    # Set default credentials
    config.add_section("mist.credentials")
    config.set("mist.credentials", "email", None)
    config.set("mist.credentials", "password", None)

    # Read configuration file
    if os.path.isfile(config_path):
            config.readfp(open(config_path))

    mist_uri = config.get("mist.io", "mist_uri")
    if not mist_email:
        mist_email = config.get("mist.credentials", "email") or ""

    if not mist_password:
        mist_password = config.get("mist.credentials", "password") or ""

    return init_client(mist_uri, mist_email, mist_password)


def init_client(mist_uri="https://mist.io", email=None, password=None):
    client = MistClient(mist_uri, email, password)
    return client


def list_images(module, client):
    backend_name = module.params.get('backend')
    backend = client.search_backend(backend_name)

    if not backend:
        module.fail_json(msg="You have to provide a valid backend id or name")

    search = module.params.get('search')

    if not search:
        images = []
        for image in backend.images:
            if image['star']:
                images.append(image)
    elif search == "all":
        images = backend.images
    else:
        images = backend.search_image(search)

    return images


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'),
            backend=dict(required=True, type='str'),
            search=dict(required=False, type='str')
        )
    )

    client = authenticate(module)

    images = list_images(module, client)

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


main()