import {ReferenceInput} from '../../index'

import {materializeReferences, referenceSearch, fetch} from '../data/fetch'
import {once} from 'lodash'
import {materializeForPreview, resolveRefType} from 'part:@sanity/base/preview'


const ReferenceBrowser = ReferenceInput.createBrowser({
  fetch,
  materializeReferences
})

export function materializeReference(id) {
  return materializeReferences([id]).then(res => res[0])
}

function valueToString(value, type) {
  return resolveRefType(value, type)
    .then(refType => materializeForPreview(value, refType))
    .then(res => res.title)
}

const ReferenceSearchableSelect = ReferenceInput.createSearchableSelect({
  search: referenceSearch,
  valueToString: valueToString
})

const ReferenceSelect = ReferenceInput.createSelect({
  fetchAll: fetch,
  materializeReferences
})

// eslint-disable-next-line no-console
const warnNoSearchYet = once(() => console.warn('Reference browser does not yet support search'))

export default function resolveReference(type) {
  const options = type.options || {}
  if (options.inputType === 'select') {
    return options.searchable
      ? ReferenceSearchableSelect
      : ReferenceSelect
  }

  if (options.inputType === 'browser') {
    if (options.searchable) {
      warnNoSearchYet()
    }
    return ReferenceBrowser
  }

  return ReferenceSearchableSelect
}

@@ -149,26 +149,22 @@
 import %7B
-materializ
+observ
 eForPrev
@@ -415,16 +415,271 @@
 %5B0%5D)%0A%7D%0A%0A
+function observableToPromise(observable) %7B%0A  return new Promise((resolve, reject) =%3E %7B%0A    const subscription = observable.subscribe(%7B%0A      next: val =%3E %7B%0A        subscription.unsubscribe()%0A        resolve(val)%0A      %7D,%0A      error: reject%0A    %7D)%0A  %7D)%0A%7D%0A
 function
@@ -766,26 +766,42 @@
 Type =%3E 
-materializ
+observableToPromise(observ
 eForPrev
@@ -820,16 +820,17 @@
 efType))
+)
 %0A    .th

Fix broken references wrt previews