import { DataCapsule, PatternsErrorHandler } from '@wix/bex-core';

export interface ColumnSizesServiceParams {
  readonly storage: DataCapsule;
  readonly fqdn: string;
  readonly errorHandler: PatternsErrorHandler;
}

export interface ColumnSizesSchema {
  columnWidths?: Record<string, number>;
}

export class ColumnSizesService {
  readonly storage;
  readonly fqdn;
  readonly errorHandler;
  private storageKey: string;

  constructor(params: ColumnSizesServiceParams) {
    this.storage = params.storage;
    this.fqdn = params.fqdn;
    this.errorHandler = params.errorHandler;
    this.storageKey = `cairo-column-sizes`;
  }

  async fetchColumnSizes(): Promise<ColumnSizesSchema | null> {
    const { storage, storageKey } = this;
    try {
      const data = await storage.getItem<ColumnSizesSchema | null>(storageKey);

      return data;
    } catch (error) {
      return null;
    }
  }

  async updateColumnWidths(
    columnWidths: Record<string, number>,
  ): Promise<void> {
    const { storage, storageKey, errorHandler } = this;
    await errorHandler.withErrorHandler(() => {
      return storage.setItem(storageKey, { columnWidths });
    }, {});
  }
}
