import { isEmpty } from 'lodash';
import { WixPatternsContainer } from '@wix/bex-core';
import { SchemaFieldsState, SchemaViewConfig } from './SchemaFieldsState';

export interface SchemaCardStateParams {
  /**
   * Field definitions for persistency. Each field's visibility and order are
   * stored per `persistencyKey` so users' layout preferences survive page reloads.
   */
  fields: SchemaViewConfig[];
  /**
   * A unique key identifying this schema card, used as the storage namespace.
   * Should be unique per card type within the app (e.g. 'contacts', 'products').
   */
  persistencyKey: string;
  container: WixPatternsContainer;
}

export class SchemaCardState {
  readonly fieldsState: SchemaFieldsState;

  constructor(params: SchemaCardStateParams) {
    if (isEmpty(params.fields)) {
      console.warn(
        'SchemaCardState: `fields` is empty — field persistency will not be enabled.',
      );
    }
    const { componentId, artifactId } = params.container.environment;
    const namespace = [componentId || artifactId, params.persistencyKey].join(
      '.',
    );
    const dataCapsule = params.container._createComponentSettings({
      namespace,
    });
    this.fieldsState = new SchemaFieldsState({
      dataCapsule,
      fields: params.fields,
    });
  }

  init() {
    this.fieldsState.init();
  }
}
