"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.loadStories = void 0;
var _cluster = _interopRequireDefault(require("cluster"));
var _selenium = require("../../selenium");
var _messages = require("../../messages");
var _types = require("../../../types");
var _logger = require("../../logger");
var _shared = require("../../../shared");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
const loadStories = async (_config, _options, storiesListener) => {
  if (_cluster.default.isPrimary) {
    return new Promise(resolve => {
      const worker = Object.values(_cluster.default.workers ?? {}).filter(_types.isDefined).find(worker => worker.isConnected());
      if (worker) {
        const unsubscribe = (0, _messages.subscribeOnWorker)(worker, 'stories', message => {
          if (message.type == 'set') {
            const {
              stories,
              oldTests
            } = message.payload;
            if (oldTests.length > 0) _logger.logger.warn(`If you use browser stories provider of CSFv3 Storybook feature\n` + `Creevey will not load tests defined in story parameters from following stories:\n` + oldTests.join('\n'));
            unsubscribe();
            resolve(stories);
          }
        });
        (0, _messages.sendStoriesMessage)(worker, {
          type: 'get'
        });
      }
      (0, _messages.subscribeOn)('stories', message => {
        // TODO updates only one browser :(
        if (message.type == 'update') storiesListener(new Map(message.payload));
      });
    });
  } else {
    (0, _messages.subscribeOn)('stories', message => {
      if (message.type == 'get') (0, _messages.emitStoriesMessage)({
        type: 'set',
        payload: {
          stories,
          oldTests: storiesWithOldTests
        }
      });
      if (message.type == 'update') storiesListener(new Map(message.payload));
    });
    const stories = (0, _shared.deserializeRawStories)(await (0, _selenium.loadStoriesFromBrowser)());
    const storiesWithOldTests = [];
    Object.values(stories).forEach(story => {
      var _parameters;
      if ((_parameters = story.parameters) !== null && _parameters !== void 0 && (_parameters = _parameters.creevey) !== null && _parameters !== void 0 && _parameters.tests) {
        var _parameters2;
        (_parameters2 = story.parameters) === null || _parameters2 === void 0 || (_parameters2 = _parameters2.creevey) === null || _parameters2 === void 0 || delete _parameters2.tests;
        storiesWithOldTests.push(`${story.kind}/${story.name}`);
      }
    });
    return stories;
  }
};
exports.loadStories = loadStories;