import { mapValues, mergeWith, cloneDeepWith } from 'lodash';
import { deserializeRegExp, isSerializedRegExp, isRegExp, serializeRegExp } from './serializeRegExp';

// NOTE: Copy-paste from storybook/api
export const combineParameters = function () {
  for (var _len = arguments.length, parameterSets = new Array(_len), _key = 0; _key < _len; _key++) {
    parameterSets[_key] = arguments[_key];
  }
  return (
    // eslint-disable-next-line @typescript-eslint/no-unsafe-return
    mergeWith({}, ...parameterSets, (_, srcValue) => {
      // Treat arrays as scalars:
      if (Array.isArray(srcValue)) return srcValue;
      return undefined;
    })
  );
};

// NOTE: Copy-paste from storybook/api
export const denormalizeStoryParameters = _ref => {
  let {
    globalParameters,
    kindParameters,
    stories
  } = _ref;
  return mapValues(stories, storyData => ({
    ...storyData,
    parameters: combineParameters(globalParameters, kindParameters[storyData.kind] ?? {}, storyData.parameters)
  }));
};
export const serializeRawStories = stories => {
  return mapValues(stories, storyData => {
    const creevey = storyData.parameters.creevey;
    if (creevey?.skip) {
      return {
        ...storyData,
        parameters: {
          ...storyData.parameters,
          creevey: {
            ...creevey,
            skip: cloneDeepWith(creevey.skip, value => {
              if (isRegExp(value)) {
                return serializeRegExp(value);
              }
              return undefined;
            })
          }
        }
      };
    }
    return storyData;
  });
};
export const deserializeRawStories = stories => {
  return mapValues(stories, deserializeStory);
};
export const deserializeStory = story => {
  const creevey = story.parameters.creevey;
  if (creevey?.skip) {
    return {
      ...story,
      parameters: {
        ...story.parameters,
        creevey: {
          ...creevey,
          skip: cloneDeepWith(creevey.skip, value => {
            if (isSerializedRegExp(value)) {
              return deserializeRegExp(value);
            }
            return undefined;
          })
        }
      }
    };
  }
  return story;
};