---
- name: "Initialize VARs"
  set_fact:
    api_path: '/s/{{ es_space }}/api/saved_objects'
    es_object_type: dashboard
    dashboard_exists: False
    elastic_dashboard_cleaned: {}
    ref_obj_modified: {}

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

- name: "Lookup dashboard object"
  set_fact:
    lookup_dashboard_object: '{{ all_dashboards.json | community.general.json_query(querystr1) | first | community.general.json_query(dashboard_query) }}'
  vars:
    querystr1: "[saved_objects[*]]"
    dashboard_query: "[?attributes.title=='{{ elastic_dashboard.attributes.title }}']"

- name: "Set switch VAR"
  set_fact:
    dashboard_exists: True
  when:
    - lookup_dashboard_object | length > 0

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


### begin of block
- name: 'Dashboards: Lookup ID of search'
  delegate_to: localhost
  block:
  - name: "Dashboards: Get all searches in elasticsearch"
    delegate_to: localhost
    uri:
      url: "https://{{ kibana_api_endpoint }}/s/{{ es_space }}/api/saved_objects/_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"
    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_dashboard.references[0].search_refname }}']"

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

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

  - name: "Set VAR"
    set_fact:
      panelindex_uuid: '{{ elastic_dashboard.references[0].search_refname | to_uuid }}'

  - name: "Doing evil string concatination with ansible in addition with variables"
    delegate_to: localhost
    set_fact:
      panelsjson: '{{ (''[ { "version":"7.16.1","type":"search","gridData":{"x":0,"y":0,"w":48,"h":28,"i":"'' + ( panelindex_uuid | string ) + ''"},"panelIndex":"'' + ( panelindex_uuid | string ) + ''","embeddableConfig":{"enhancements":{} },"panelRefName":"panel_'' + ( panelindex_uuid | string ) + ''" } ]'') | string }}'

  - 
    name: "Prepare step for merging dashboard objects"
    delegate_to: localhost
    set_fact:
      ref_obj_modified:
        attributes:
          title: '{{ elastic_dashboard.attributes.title }}'
          panelsJSON: '{{ panelsjson | string }}'
        references:
          -
            name: '{{ panelindex_uuid }}'
            type: 'search'
            id: '{{ lookup_search_object[0].id }}'
    when:
      - lookup_search_object | length > 0
  when:
    - elastic_dashboard.elastic_state == 'present'
### end of block

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

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

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

- name: "Create {{ es_object_type }} <<{{ elastic_dashboard.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_dashboard_cleaned | to_json }}'
  become: false
  when:
    - not dashboard_exists
    - elastic_dashboard.elastic_state == 'present'

- name: "Update {{ es_object_type }} <<{{ elastic_dashboard.attributes.title }}>>"
  delegate_to: localhost
  uri:
    url: 'https://{{ kibana_api_endpoint }}{{ api_path }}/{{ es_object_type }}/{{ lookup_dashboard_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_dashboard_cleaned | to_json }}'
  become: false
  when:
    - dashboard_exists
    - elastic_dashboard.elastic_state == 'present'

- name: "DELETE {{ es_object_type }} <<{{ elastic_dashboard.attributes.title }}>>"
  delegate_to: localhost
  uri:
    url: 'https://{{ kibana_api_endpoint }}{{ api_path }}/{{ es_object_type }}/{{ lookup_dashboard_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:
    - dashboard_exists
    - elastic_dashboard.elastic_state == 'absent'
