import joi from 'joi';
import { FormComponent, isFormValue } from "./FormComponent.js";
import { addClassOptionIfNone } from "./helpers/index.js";
import { markdown } from "./markdownParser.js";
import { messageTemplate } from "../pageControllers/validationOptions.js";
/**
 * Abstract base class for location-based field components
 */
export class LocationFieldBase extends FormComponent {
  instructionText;
  constructor(def, props) {
    super(def, props);
    const {
      options
    } = def;
    const locationOptions = options;
    this.instructionText = locationOptions.instructionText;
    addClassOptionIfNone(locationOptions, 'govuk-input--width-10');
    const config = this.getValidationConfig();
    let formSchema = joi.string().trim().label(this.label).required().pattern(config.pattern).messages({
      'string.pattern.base': config.patternErrorMessage,
      ...config.additionalMessages
    });
    if (config.customValidation) {
      formSchema = formSchema.custom(config.customValidation);
    }
    if (locationOptions.required === false) {
      formSchema = formSchema.allow('');
    }
    if (locationOptions.customValidationMessage) {
      const message = locationOptions.customValidationMessage;
      const messageKeys = ['any.required', 'string.empty', 'string.pattern.base'];
      if (config.additionalMessages) {
        messageKeys.push(...Object.keys(config.additionalMessages));
      }
      const messages = messageKeys.reduce((acc, key) => {
        acc[key] = message;
        return acc;
      }, {});
      formSchema = formSchema.messages(messages);
    } else if (locationOptions.customValidationMessages) {
      formSchema = formSchema.messages(locationOptions.customValidationMessages);
    }
    this.formSchema = formSchema.default('');
    this.stateSchema = formSchema.default(null).allow(null);
    this.options = locationOptions;
  }
  getFormValueFromState(state) {
    const {
      name
    } = this;
    return this.getFormValue(state[name]);
  }
  getFormValue(value) {
    return this.isValue(value) ? value : undefined;
  }
  isValue(value) {
    return LocationFieldBase.isText(value);
  }
  getViewModel(payload, errors) {
    const viewModel = super.getViewModel(payload, errors);
    if (this.instructionText) {
      return {
        ...viewModel,
        instructionText: markdown.parse(this.instructionText, {
          async: false
        })
      };
    }
    return viewModel;
  }
  getAllPossibleErrors() {
    return {
      baseErrors: [{
        type: 'required',
        template: messageTemplate.required
      }, ...this.getErrorTemplates()],
      advancedSettingsErrors: []
    };
  }
  static isText(value) {
    return isFormValue(value) && typeof value === 'string';
  }
}
//# sourceMappingURL=LocationFieldBase.js.map