package alraune

import aplight.GelNew
import pieces100.*
import vgrechka.*

@GelNew
class UserPickerValue {
    var id by notNull<Long>()
    var text by notNull<String>()
}

fun composeUserPicker__killme(forceId: String? = null, initial: UserPickerValue? = null): AlTag {
    val select = select().style("width: 100%;")
    forceId?.let {select.id(it)}

    val code = StringBuilder()
    code.ln("""
        ${select.jq()}.select2({
              ajax: {
                url: "${UserSearchWebApi.path}",
                dataType: 'json',
                delay: 250,
                data: function (params) {
                  return {
                    q: params.term, // search term
                    page: params.page
                  };
                },
                processResults: function (data, params) {
                  // parse the results into the format expected by Select2
                  // since we are using custom formatting functions we do not need to
                  // alter the remote JSON data, except to indicate that infinite
                  // scrolling can be used
                  params.page = params.page || 1;

                  return {
                    results: data.items,
                    pagination: {
                      more: (params.page * ${UserSearchWebApi.pageSize}) < data.totalCount
                    }
                  };
                },
                cache: true
              },
              placeholder: 'Поиск засранца',
              escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
              minimumInputLength: 1,
              templateResult: formatFucker,
              templateSelection: formatFuckerSelection,
            })

            function formatFucker (fucker) {
              if (fucker.loading) {
                return ${TS.alraune.escapeHTML}(fucker.text);
              }

              var markup = "<div>" + ${TS.alraune.escapeHTML}(fucker.text) + "</div>"

              return markup
            }

            function formatFuckerSelection (fucker) {
              return ${TS.alraune.escapeHTML}(fucker.text)
            }
    """)

    if (initial != null) {
        code.ln("""
            const data = ${jsonize(initial)}
            var option = new Option(data.text, data.id, true, true)
            ${select.jq()}.append(option).trigger('change')

            // manually trigger the `select2:select` event
            ${select.jq()}.trigger({
                type: 'select2:select',
                params: {
                    data: data
                }
            })
        """)
    }

    Context1.get().jsOnDomReady.appendIife(code.toString())

    return select
}



