import { env } from '../helpers'

export default class ValidationController {

  /**
   *
   * @param array
   * @param schema
   * @returns {*[]}
   */
  static allAgainstSchema (array, schema) {
    const objs = []

    array.forEach(obj => {
      const res = this.againstSchema(obj, schema)

      if (res.status === true) {
        objs.push(res.data)
      }

    })

    return objs
  }

  /**
   * @param obj
   * @param obj.key => schema.key
   * @param obj.values => [ <required>: boolean, <regexp_pattern>: string ]
   * @param schema
   * @returns {{error_text: *[], data: {}, errors: *[], status: boolean}}
   */
  static againstSchema (obj, schema) {

    const out = {
      status: false,
      error_text: [],
      data: {},
      errors: [],
    }

    try {

      for (const [key, value] of Object.entries(schema)) {
        const field = (obj[key] || '').toString().trim()

        if (field !== '') {

          if (typeof value[1] !== 'number') {
            const regex = new RegExp(value[1].toString(), 'i')

            if (regex.exec(field)) {
              out.data[key] = field

            } else {

              if (value[0]) {
                out.errors.push(key)
                out.error_text.push(`${key} is required`)
              }
            }
          } else if (field.length > 0) {
            out.data[key] = field.slice(0, value[1])
          }

        } else {

          if (value[0]) {
            out.errors.push(key)
            out.error_text.push(`${key} is empty`)
          }
        }
      }

    } catch (e) {
      out.error_text.push(`Critical error! ` + e.toString())
    }

    out.status = !(out.error_text.length > 0 && out.errors.length > 0)

    return out
  }

  /**
   *
   * @param node
   */
  static lengthOnKeyUp (node) {
    const logger = document.querySelector(`[for='${node.id}'] > span`)
    logger.innerHTML = `${node.value.length}/${env.schemas.note[node.getAttribute('name')][1]}`

    node.value.length > env.schemas.note[node.getAttribute('name')][1]
      ? logger.classList.add('uk-text-danger')
      : logger.classList.remove(
        'uk-text-danger')
  }

}