import Joi from 'joi';

import IdValidate from './id';
import globals from '../../globals';

export default class MeasurementValidate {
  private static measurement = {
    values: Joi.object()
      .pattern(/.*/, Joi.alternatives()
        .try(
          Joi.string().max(128),
          Joi.number(),
          Joi.boolean(),
          Joi.array().items(Joi.array().items(Joi.number())),  // for spectra
          Joi.array()
        )
        .allow(null)
      )
  };

  static input (data, param) {  // validate input, set param to 'new' to make all attributes required
    if (param === 'new') {
      return Joi.object({
        sample_id: IdValidate.get().required(),
        values: this.measurement.values.required(),
        measurement_template: IdValidate.get().required()
      }).validate(data);
    }
    else if (param === 'change') {
      return Joi.object({
        values: this.measurement.values
      }).validate(data);
    }
    else {
      return{error: 'No parameter specified!', value: {}};
    }
  }

  // validate output and strip unwanted properties, returns null if not valid
  static output (data, req, status = false) {
    data = IdValidate.stringify(data);
    // spectral data not allowed for read/write users
    if (['dev', 'admin'].indexOf(req.authDetails.level) < 0 && data.values[globals.spectrum.dpt]) {
      delete data.values[globals.spectrum.dpt];
    }
    const validation: any = {
      _id: IdValidate.get(),
      sample_id: IdValidate.get(),
      values: this.measurement.values,
      measurement_template: IdValidate.get()
    };
    if (status) {
      validation.status = Joi.string().valid(...Object.values(globals.status));
    }
    const {value, error} = Joi.object(validation).validate(data, {stripUnknown: true});
    return error !== undefined? null : value;
  }

  static outputV() {  // return output validator
    return Joi.object({
      _id: IdValidate.get(),
      sample_id: IdValidate.get(),
      values: this.measurement.values,
      measurement_template: IdValidate.get()
    });
  }
}