---
- name: "Initialze VARs"
  set_fact:
    api_path: '/s/{{ es_space }}/api/saved_objects'
    es_object_type: search
    search_exists: False
    elastic_search_cleaned: {}
    ref_obj_modified: {}

- name: "Get all searches in elasticsearch"
  delegate_to: localhost
  uri:
    url: "https://{{ kibana_api_endpoint }}{{ api_path }}/_find?per_page=10000&type=search"
    method: GET
    status_code: [200]
    user: "{{ elastic_admin_username }}" 
    password: "{{ elastic_admin_password }}"
    force_basic_auth: yes
  register: all_searches
  become: false

- name: "Lookup search object if exists"
  set_fact:
    lookup_search_object: '{{ all_searches.json | community.general.json_query(querystr1) | first | community.general.json_query(search_query) }}'
  vars:
    querystr1: "[saved_objects[*]]"
    search_query: "[?attributes.title=='{{ elastic_search.attributes.title }}']"

- name: "Set switch VAR"
  set_fact:
    search_exists: True 
  when:
    - lookup_search_object | length > 0

- name: "Drop not needed keys from dict"
  set_fact:
    elastic_search_cleaned: "{{ elastic_search_cleaned | combine({item.key: item.value}) }}"
  with_dict: '{{ elastic_search }}'
  when:
    - item.key not in ['elastic_state']

### begin of block
- name: 'Lookup ID of indexpattern'
  delegate_to: localhost
  block:
  - name: "Get all indexpatterns in elasticsearch"
    delegate_to: localhost
    uri:
      url: "https://{{ kibana_api_endpoint }}/s/{{ es_space }}/api/saved_objects/_find?per_page=10000&type=index-pattern"
      method: GET
      status_code: [200]
      user: "{{ elastic_admin_username }}" 
      password: "{{ elastic_admin_password }}"
      force_basic_auth: yes
    register: all_indexpatterns
    become: false
  
  - name: "Lookup index pattern object if exists"
    set_fact:
      lookup_indexpattern_object: '{{ all_indexpatterns.json | community.general.json_query(querystr1) | first | community.general.json_query(indexpattern_query) }}'
    vars:
      querystr1: "[saved_objects[*]]"
      indexpattern_query: "[?attributes.title=='{{ elastic_search.references[0].ref_name }}']"
  
  - name: "Set switch VAR"
    set_fact:
      indexpattern_exists: True 
    when:
      - lookup_indexpattern_object | length > 0
  
  - name: "DEBUG"
    debug:
      msg: 'lookup_indexpattern_object:{{ lookup_indexpattern_object }}'

  - 
    name: "Prepare step to combine dicts"
    delegate_to: localhost
    set_fact:
      ref_obj_modified:
        references:
          -
            name: '{{ elastic_search.references[0].name }}'
            type: 'index-pattern'
            id: '{{ lookup_indexpattern_object[0].id }}' 
    when:
      - lookup_indexpattern_object | length > 0
  when:
    - elastic_search.elastic_state == 'present'
### end of block

- name: "Kick out not needed keys in search dict"
  delegate_to: localhost
  set_fact:
    elastic_search_cleaned: "{{ elastic_search_cleaned | combine( { item.key: item.value } ) }}"
  with_dict: '{{ elastic_search }}'
  when:
    - item.key not in ['elastic_state','references']

- name: "Crafting new search object to throw it against ES-API"
  delegate_to: localhost
  set_fact:
    elastic_search_cleaned: "{{ elastic_search_cleaned | combine( ref_obj_modified ) }}"

- name: "DEBUG"
  debug:
    msg: 'DEBUG elastic_search_cleaned: {{ elastic_search_cleaned }}'


- name: "Create {{ es_object_type }} <<{{ elastic_search.attributes.title }}>>"
  delegate_to: localhost
  uri:
    url: "https://{{ kibana_api_endpoint }}{{ api_path }}/{{ es_object_type }}"
    method: POST
    status_code: [200]
    user: "{{ elastic_admin_username }}" 
    password: "{{ elastic_admin_password }}"
    force_basic_auth: yes
    headers:
      Content-Type: application/json
      kbn-xsrf: true
    body_format: json
    body: '{{ elastic_search_cleaned | to_json }}'
  become: false
  when:
    - not search_exists
    - elastic_search.elastic_state == 'present'

- name: "Update {{ es_object_type }} <<{{ elastic_search.attributes.title }}>>"
  delegate_to: localhost
  uri:
    url: 'https://{{ kibana_api_endpoint }}{{ api_path }}/{{ es_object_type }}/{{ lookup_search_object[0]["id"] }}'
    method: PUT
    status_code: [200]
    user: "{{ elastic_admin_username }}" 
    password: "{{ elastic_admin_password }}"
    force_basic_auth: yes
    headers:
      Content-Type: application/json
      kbn-xsrf: true
    body_format: json
    body: '{{ elastic_search_cleaned | to_json }}'
  become: false
  when:
    - search_exists
    - elastic_search.elastic_state == 'present'

- name: "DELETE {{ es_object_type }} <<{{ elastic_search.attributes.title }}>>"
  delegate_to: localhost
  uri:
    url: 'https://{{ kibana_api_endpoint }}{{ api_path }}/{{ es_object_type }}/{{ lookup_search_object[0]["id"] }}'
    method: DELETE
    status_code: [200]
    user: "{{ elastic_admin_username }}" 
    password: "{{ elastic_admin_password }}"
    force_basic_auth: yes
    headers:
      Content-Type: application/json
      kbn-xsrf: true
  become: false
  when:
    - search_exists
    - elastic_search.elastic_state == 'absent'
