import create from './dom/create'
import onFind from './dom/onFind'

// Federated Search Enchancements
// https://github.com/perfectsense/docs-internal/blob/feature/contextual-federated-search/v4/patch-2/federated-search-enhancements.txt
// Add the new external items to the search results.
onFind('.ExternalItemObjects', (objects) => {
  const source = $(objects).popup('source')

  if (source) {
    const forms = source[0]
      ?.closest('.searchForm')
      ?.querySelectorAll<HTMLFormElement>(
        ':scope > .searchControls > .searchFilters > form',
      )

    if (forms?.length) {
      const form = forms[0]
      objects
        .querySelectorAll<HTMLInputElement>(
          ':scope > input[name="newObjectId"]',
        )
        .forEach(function (input) {
          const newInput = create('input', {
            type: 'hidden',
            name: 'ni',
            value: input.value,
          })
          form.appendChild(newInput)
        })
      form.requestSubmit()
    }
  }

  $(objects).popup('close')
})
