.. versionadded:: 2015.8.0
    .. versionchanged:: 2017.3.0
        Marked ``definition`` as optional.

    Ensure that the named index is present.

    name
        Name of the index to add

    definition
        Optional dict for creation parameters as per https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-create-index.html

    **Example:**

    .. code-block:: yaml

        # Default settings
        mytestindex:
          elasticsearch_index.present

        # Extra settings
        mytestindex2:
          elasticsearch_index.present:
            - definition:
                settings:
                  index:
                    number_of_shards: 10

def present(name, definition=None):
    '''
    .. versionadded:: 2015.8.0
    .. versionchanged:: 2017.3.0
        Marked ``definition`` as optional.

    Ensure that the named index is present.

    name
        Name of the index to add

    definition
        Optional dict for creation parameters as per https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-create-index.html

    **Example:**

    .. code-block:: yaml

        # Default settings
        mytestindex:
          elasticsearch_index.present

        # Extra settings
        mytestindex2:
          elasticsearch_index.present:
            - definition:
                settings:
                  index:
                    number_of_shards: 10
    '''

    ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}

    try:
        index_exists = __salt__['elasticsearch.index_exists'](index=name)
        if not index_exists:
            if __opts__['test']:
                ret['comment'] = 'Index {0} does not exist and will be created'.format(name)
                ret['changes'] = {'new': definition}
                ret['result'] = None
            else:
                output = __salt__['elasticsearch.index_create'](index=name, body=definition)
                if output:
                    ret['comment'] = 'Successfully created index {0}'.format(name)
                    ret['changes'] = {'new': __salt__['elasticsearch.index_get'](index=name)[name]}
                else:
                    ret['result'] = False
                    ret['comment'] = 'Cannot create index {0}, {1}'.format(name, output)
        else:
            ret['comment'] = 'Index {0} is already present'.format(name)
    except Exception as err:
        ret['result'] = False
        ret['comment'] = six.text_type(err)

    return ret