import { makeAutoObservable } from 'mobx';
import { FormType, FormV2 } from './FormV2';
import { List } from '../List';

export class Forms {
  forms: List<FormV2>;
  updated: number;

  constructor() {
    this.forms = new List<FormV2>();
    this.updated = new Date().getTime();
    makeAutoObservable(this);
  }

  init = (form: FormType) => {
    const formId = form.id;
    if (!formId) {
      throw new Error('Form id is required');
    }
    const currentForm = this.getForm(formId);
    if (currentForm) {
      // don't initialize if already exists
      return currentForm;
    }
    this.forms.set(new FormV2(form));
    return this.getForm(formId);
  };

  deleteForm = (formId: string) => {
    this.forms.delete(formId);
  };

  getForm = (formId: string) => {
    return this.forms.get(formId);
  };

  getFormData = (formId: string) => {
    return this.getForm(formId)?.data;
  };
}

export const forms = new Forms();
