import { makeAutoObservable } from 'mobx';
import notification from 'ui/elements/notification';
import type { ValidationConfig } from './types';

export default class Validation {
  params: ValidationConfig;
  messages: Set<string>;

  constructor(config: ValidationConfig) {
    this.params = config;
    this.messages = new Set();
    makeAutoObservable(this);
  }

  get hasErrors() {
    return this.messages.size > 0;
  }

  getMessages() {
    return [...this.messages];
  }

  removeError = (message: string) => {
    this.messages.delete(message);
    if (this.messages.size === 0) notification.close(this.params.err_key);
  };

  addError = (message: string) => {
    this.messages.add(message);

    notification.error({
      key: this.params.err_key,
      message: this.params.err_title,
      description: message,
    });

    return () => this.removeError(message);
  };

  clearErrors = () => {
    this.messages.clear();
    notification.close(this.params.err_key);
  };
}
