const { MEMBER_SEPARATOR, NULL_CHARACTER } = require('./constants')
const createEvent = require('./createEvent')
const getLoader = require('./getLoader')
const v = require('./validate')

// TODO: refactor to eliminate code duplication (searchByValue, searchByValueIgnoreCase).

/**
 * Searches for events with a value either equal to the given value or starting with it, ignoring case.
 *
 * @function EntityAttribute#searchByValueIgnoreCase
 * @param {?String} value The given value.
 * @param {('ascending'|'descending')} [order='ascending'] The order of the returned events.
 * @param {Function} done
 * @returns {Array.<Event>} An array of matching events.
 */
module.exports = function EntityAttribute$searchByValueIgnoreCase(value, aOrder, aDone) {
    let order
    let done

    if (typeof aOrder === 'function') {
        order = 'ascending'
        done = aOrder
    } else {
        order = aOrder
        done = aDone
    }

    if (!v.callback(done, "argument 3, 'done'")) {
        throw v.lastError
    }

    const canBeNull = this._isNullable
    if (!v.value(value, canBeNull, "argument 1, 'value'")) {
        done(v.lastError)
        return
    }

    if (!v.order(order, "argument 2, 'order'")) {
        done(v.lastError)
        return
    }

    const client = this._client
    const isCaseSensitive = false

    getLoader(client).load('searchByValue', (err, sha) => {
        if (err) {
            done(err)
            return
        }

        client.evalsha(
            sha,
            0,
            this._keyPrefix,
            isCaseSensitive,
            MEMBER_SEPARATOR,
            value,
            order,
            (err, reply) => {
                if (err) {
                    done(err)
                    return
                }

                // TODO: move to constructor
                const transform = isCaseSensitive
                    ? r => {
                          const [value, createdAt, entityId] = r.split(MEMBER_SEPARATOR)
                          return createEvent(NULL_CHARACTER, entityId, value, createdAt)
                      }
                    : r => {
                          const [createdAt, entityId, value] = r.split(MEMBER_SEPARATOR).slice(1)
                          return createEvent(NULL_CHARACTER, entityId, value, createdAt)
                      }

                done(null, reply.map(transform))
            }
        )
    })
}

{'avg_line_length': 29.265060240963855, 'max_line_length': 103, 'alphanum_fraction': 0.5397282832441334, 'licenses': ['MIT'], 'repository_name': 'adriano-di-giovanni/reaves', 'path': 'lib/EntityAttribute/searchByValueIgnoreCase.js', 'size': 2429, 'lang': 'JavaScript'}