import { assert, fixture, html, aTimeout } from '@open-wc/testing'
import { AmfDefinitions } from '@api-client/core/browser.js'
import { AmfLoader } from '../AmfLoader.js'
import * as InputCache from '../../../src/amf/lib/InputCache.js'
import { DomEventsAmfStore } from '../../../src/index.js'
import ApiRequestEditorElement from '../../../src/elements/amf/ApiRequestEditor.element.js'
import '../../../src/define/amf/api-request-editor.js'

describe('ApiRequestEditorElement', () => {
  describe('SE-12957', () => {
    const store = new DomEventsAmfStore(window)
    store.listen()
    const apiFile = 'SE-12957'

    /*
     * This issue is about rendering URI parameters in the operation parameters,
     * as URI parameters can appear in the Server, Endpoint, and Operation model.
     */

    async function modelFixture(domainId: string): Promise<ApiRequestEditorElement> {
      const element = await fixture(html`<api-request-editor .domainId="${domainId}"></api-request-editor>`)
      await aTimeout(2)
      return element as ApiRequestEditorElement
    }

    let loader: AmfLoader
    let amf: AmfDefinitions.IAmfDocument

    before(async () => {
      loader = new AmfLoader()
      amf = await loader.getGraph(apiFile)
      store.amf = amf
    })

    it('renders the input for the URI parameter', async () => {
      const method = loader.lookupOperation(
        amf,
        '/api/v1/alarm/{scada-object-key}',
        'get'
      ) as AmfDefinitions.IAmfOperation
      const methodId = method['@id']
      const editor = await modelFixture(methodId)
      const input = editor.shadowRoot!.querySelector('[name="scada-object-key"]')
      assert.ok(input)
    })

    //
    // accidentally I discovered that the `dateTime` input is not rendering correctly
    // after updating the cached values.
    //

    it('renders the dateTime query parameter', async () => {
      const method = loader.lookupOperation(
        amf,
        '/api/v1/alarm/{scada-object-key}',
        'get'
      ) as AmfDefinitions.IAmfOperation
      const methodId = method['@id']
      const editor = await modelFixture(methodId)
      const input = editor.shadowRoot!.querySelector('[name="time-on"]')
      assert.ok(input)
    })

    it('sets the proper value on the dateTime parameter', async () => {
      const method = loader.lookupOperation(
        amf,
        '/api/v1/alarm/{scada-object-key}',
        'get'
      ) as AmfDefinitions.IAmfOperation
      const methodId = method['@id']
      const editor = await modelFixture(methodId)
      const input = editor.shadowRoot!.querySelector('[name="time-on"]') as HTMLInputElement
      // this is valid value but the <input> filed ignores this format.
      InputCache.set(editor, input.dataset.domainId as string, '2021-09-27T14:55:33.688Z', true)
      editor.requestUpdate()
      await editor.updateComplete
      assert.equal(input.value, '2021-09-27T14:55:33.688')
    })
  })
})
