/**
 * Copyright (c) Tiny Technologies, Inc. All rights reserved.
 * Licensed under the LGPL or a commercial license.
 * For LGPL see License.txt in the project root for license information.
 * For commercial licenses see https://www.tiny.cloud/
 */

import { Arr, Cell, Results } from '@ephox/katamari';

import { PatternSet, RawPattern } from '../core/PatternTypes';
import { createPatternSet, denormalizePattern, normalizePattern } from './Pattern';

export interface Api {
  readonly setPatterns: (newPatterns: RawPattern[]) => void;
  readonly getPatterns: () => RawPattern[];
}

const get = (patternsState: Cell<PatternSet>): Api => {
  const setPatterns = (newPatterns: RawPattern[]) => {
    const normalized = Results.partition(Arr.map(newPatterns, normalizePattern));
    if (normalized.errors.length > 0) {
      const firstError = normalized.errors[0];
      throw new Error(firstError.message + ':\n' + JSON.stringify(firstError.pattern, null, 2));
    }
    patternsState.set(createPatternSet(normalized.values));
  };

  const getPatterns = () => [
    ...Arr.map(patternsState.get().inlinePatterns, denormalizePattern),
    ...Arr.map(patternsState.get().blockPatterns, denormalizePattern)
  ];

  return {
    setPatterns,
    getPatterns
  };
};

export {
  get
};
