import { debounce, handleImageError, transparentPixel } from './utils.ts'
import { fetchNostrUser, inputToPubkey } from './nostr.ts'

export default class NostrPicture extends HTMLElement {
  static observedAttributes = ['pubkey', 'width', 'height']

  img: HTMLImageElement

  constructor() {
    super()

    this.img = document.createElement('img')
    this.img.setAttribute('part', 'img')
    this.img.onerror = handleImageError

    this.attachShadow({ mode: 'open' })
    const { shadowRoot } = this
    shadowRoot!.appendChild(this.img)
  }

  connectedCallback() {
    this.set()
  }

  attributeChangedCallback(name: string, _: string, value: string) {
    if (name === 'pubkey') this.set()
    else if (name === 'width' || name === 'height') this.img.setAttribute(name, value)
  }

  set: () => void = debounce(async () => {
    let input = this.getAttribute('pubkey')
    if (input) {
      let [pubkey, hints] = await inputToPubkey(input)
      if (pubkey) {
        let metadata = await fetchNostrUser(pubkey, hints || [])

        this.img.src = metadata.image || transparentPixel
        this.img.alt = `picture for "${metadata.shortName}"`
      }
    }
  }, 200)
}

window.customElements.define('nostr-picture', NostrPicture)
