import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties";
var _excluded = ["type", "datasourceId", "shouldMockORSBatch", "delayedResponse", "availableSitesOverride", "mockExecutionDelay", "accessibleProductsOverride"];
import _regeneratorRuntime from "@babel/runtime/regenerator";
import fetchMock from 'fetch-mock/cjs/client';
import { mockActionsDiscovery, mockActionsExecution, ORS_ACTIONS_DISCOVERY_ENDPOINT } from './actions';
import { mockAssetsClientFetchRequests } from './assets';
import { assetsDefaultInitialVisibleColumnKeys } from './assets/data';
import { successfulRecommendationAPIResponse } from './basic-filters/mocks';
import { defaultInitialVisibleColumnKeys as defaultInitialVisibleConfluenceColumnKeys } from './confluence/data';
import * as confluenceMocks from './confluence/mocks';
import { defaultInitialVisibleColumnKeys as defaultInitialVisibleJiraColumnKeys, mockAutoCompleteData, mockJiraData, mockProductsData, mockSite, mockSiteData, mockSuggestionData } from './jira/data';
import * as jiraMocks from './jira/mocks';
export { defaultInitialVisibleConfluenceColumnKeys };
export { defaultInitialVisibleJiraColumnKeys, assetsDefaultInitialVisibleColumnKeys, mockAutoCompleteData, mockJiraData, mockSiteData, mockProductsData, mockSite, mockSuggestionData, mockAssetsClientFetchRequests };
export { mockBasicFilterAGGFetchRequests } from './basic-filters/index';
export { fieldValuesEmptyResponse, fieldValuesEmptyResponseMapped, fieldValuesResponseForAssignees, fieldValuesResponseForAssigneesMapped, fieldValuesResponseForProjects, fieldValuesResponseForProjectsMapped, fieldValuesResponseForStatuses, fieldValuesResponseForStatusesMapped, fieldValuesResponseForTypes, fieldValuesResponseForTypesMapped, hydrateJqlEmptyResponse, hydrateJqlEmptyResponseMapped, hydrateJqlStandardResponse, hydrateJqlStandardResponseMapped, fieldValuesResponseForProjectsMoreData, fieldValuesResponseForStatusesSearched, fieldValuesResponseForTypesWithRelativeUrls, fieldValuesResponseForTypesWithRelativeUrlsMapped, successfulUserQueryResponse, failedUserQueryResponse, successfulRecommendationAPIResponse, failedRecommendationAPIResponse, transformedRecommendationMockFilterOptions, successfuluserHydrationResponse, hydrateJqlStandardResponseForVRTesting } from './basic-filters/mocks';
fetchMock.config.fallbackToNetwork = true;
var numberOfLoads = 0;
export var mockDatasourceFetchRequests = function mockDatasourceFetchRequests() {
  var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var _ref$type = _ref.type,
    type = _ref$type === void 0 ? 'jira' : _ref$type,
    string = _ref.datasourceId,
    _ref$shouldMockORSBat = _ref.shouldMockORSBatch,
    shouldMockORSBatch = _ref$shouldMockORSBat === void 0 ? false : _ref$shouldMockORSBat,
    _ref$delayedResponse = _ref.delayedResponse,
    delayedResponse = _ref$delayedResponse === void 0 ? true : _ref$delayedResponse,
    availableSitesOverride = _ref.availableSitesOverride,
    _ref$mockExecutionDel = _ref.mockExecutionDelay,
    mockExecutionDelay = _ref$mockExecutionDel === void 0 ? 600 : _ref$mockExecutionDel,
    accessibleProductsOverride = _ref.accessibleProductsOverride,
    rest = _objectWithoutProperties(_ref, _excluded);
  var datasourceMatcher = '[^/]+';

  // Playwright VR tests do not like setTimeout
  // eslint-disable-next-line no-unused-vars
  var setTimeoutConfigured = delayedResponse ? setTimeout : function (cb, _) {
    return cb();
  };
  var initialVisibleColumnKeys = function () {
    if (rest.initialVisibleColumnKeys) {
      return rest.initialVisibleColumnKeys;
    }
    if (type === 'jira') {
      return jiraMocks.defaultInitialVisibleColumnKeys;
    }
    if (type === 'confluence') {
      return confluenceMocks.defaultInitialVisibleColumnKeys;
    }
    return [];
  }();
  fetchMock.post(new RegExp("object-resolver/datasource/".concat(datasourceMatcher, "/fetch/details")), /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
    return _regeneratorRuntime.wrap(function _callee$(_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          return _context.abrupt("return", new Promise(function (resolve, reject) {
            if (type === 'jira') {
              var response = jiraMocks.generateDetailsResponse(initialVisibleColumnKeys);
              return resolve(response);
            }
            if (type === 'confluence') {
              var _response = confluenceMocks.generateDetailsResponse(initialVisibleColumnKeys);
              return resolve(_response);
            }
            return reject(new Error("Unhandled type ".concat(type, " when mocking fetc/details")));
          }));
        case 1:
        case "end":
          return _context.stop();
      }
    }, _callee);
  })));

  // Mock this for the editor's testing examples.
  if (shouldMockORSBatch) {
    fetchMock.post(new RegExp("object-resolver/resolve/batch"), /*#__PURE__*/function () {
      var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(url, request) {
        var getMock, requestJson, resourceUrl, mock;
        return _regeneratorRuntime.wrap(function _callee2$(_context2) {
          while (1) switch (_context2.prev = _context2.next) {
            case 0:
              getMock = function _getMock(resourceUrl) {
                if (type === 'jira') {
                  return jiraMocks.generateResolveResponse(resourceUrl);
                }
                if (type === 'confluence') {
                  return confluenceMocks.generateResolveResponse(resourceUrl);
                }
              };
              requestJson = JSON.parse(request.body);
              if (!(requestJson.length === 1)) {
                _context2.next = 7;
                break;
              }
              resourceUrl = requestJson[0].resourceUrl;
              mock = getMock(resourceUrl);
              if (!mock) {
                _context2.next = 7;
                break;
              }
              return _context2.abrupt("return", Promise.resolve([mock]));
            case 7:
              return _context2.abrupt("return", fetchMock.realFetch(url, {
                method: 'POST',
                headers: request.headers,
                body: request.body
              }));
            case 8:
            case "end":
              return _context2.stop();
          }
        }, _callee2);
      }));
      return function (_x, _x2) {
        return _ref3.apply(this, arguments);
      };
    }());
  }
  fetchMock.post(new RegExp("/gateway/api/object-resolver/datasource/".concat(datasourceMatcher, "/fetch/data")), /*#__PURE__*/function () {
    var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(url, details) {
      var requestBody, cloudId, includeSchema, fields, requestedColumnKeys, getMock;
      return _regeneratorRuntime.wrap(function _callee3$(_context3) {
        while (1) switch (_context3.prev = _context3.next) {
          case 0:
            getMock = function _getMock2() {
              if (type === 'jira') {
                return jiraMocks.generateDataResponse({
                  cloudId: cloudId,
                  numberOfLoads: numberOfLoads,
                  includeSchema: includeSchema,
                  initialVisibleColumnKeys: requestedColumnKeys
                });
              }
              if (type === 'confluence') {
                return confluenceMocks.generateDataResponse({
                  cloudId: cloudId,
                  numberOfLoads: numberOfLoads,
                  includeSchema: includeSchema,
                  initialVisibleColumnKeys: requestedColumnKeys
                });
              }
            };
            requestBody = JSON.parse(details.body);
            cloudId = requestBody.parameters.cloudId, includeSchema = requestBody.includeSchema, fields = requestBody.fields; // Mirror production: when the client requests specific `fields`, return data
            // (and schema, if requested) for those fields. Otherwise, fall back to the
            // mock's configured default visible columns.
            requestedColumnKeys = Array.isArray(fields) && fields.length > 0 ? fields : initialVisibleColumnKeys;
            return _context3.abrupt("return", new Promise(function (resolve, reject) {
              var delay = numberOfLoads * 1000;
              setTimeoutConfigured(function () {
                try {
                  var mockResponse = getMock();
                  resolve(mockResponse);
                } catch (err) {
                  reject(err);
                }
                numberOfLoads += 1;
              }, delay);
            }));
          case 5:
          case "end":
            return _context3.stop();
        }
      }, _callee3);
    }));
    return function (_x3, _x4) {
      return _ref4.apply(this, arguments);
    };
  }());
  fetchMock.post(/api\/available-sites/, /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4() {
    return _regeneratorRuntime.wrap(function _callee4$(_context4) {
      while (1) switch (_context4.prev = _context4.next) {
        case 0:
          return _context4.abrupt("return", new Promise(function (resolve) {
            resolve({
              sites: availableSitesOverride || mockSiteData
            });
          }));
        case 1:
        case "end":
          return _context4.stop();
      }
    }, _callee4);
  })));
  fetchMock.post(/api\/v2\/accessible-products/, /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5() {
    return _regeneratorRuntime.wrap(function _callee5$(_context5) {
      while (1) switch (_context5.prev = _context5.next) {
        case 0:
          return _context5.abrupt("return", new Promise(function (resolve) {
            resolve({
              data: {
                products: accessibleProductsOverride || mockProductsData
              }
            });
          }));
        case 1:
        case "end":
          return _context5.stop();
      }
    }, _callee5);
  })));
  fetchMock.get(/\/api\/ex\/jira\/.+\/\/rest\/api\/latest\/jql\/autocompletedata\/suggestions\?.+/, /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee6() {
    return _regeneratorRuntime.wrap(function _callee6$(_context6) {
      while (1) switch (_context6.prev = _context6.next) {
        case 0:
          return _context6.abrupt("return", new Promise(function (resolve) {
            var delay = 150;
            setTimeoutConfigured(function () {
              resolve(mockSuggestionData);
            }, delay);
          }));
        case 1:
        case "end":
          return _context6.stop();
      }
    }, _callee6);
  })));
  fetchMock.post(new RegExp("/gateway/api/v1/recommendations"), /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee7() {
    return _regeneratorRuntime.wrap(function _callee7$(_context7) {
      while (1) switch (_context7.prev = _context7.next) {
        case 0:
          return _context7.abrupt("return", Promise.resolve(successfulRecommendationAPIResponse));
        case 1:
        case "end":
          return _context7.stop();
      }
    }, _callee7);
  })));
  fetchMock.post(/\/api\/ex\/jira\/.+\/rest\/api\/latest\/jql\/autocompletedata/, /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee8() {
    return _regeneratorRuntime.wrap(function _callee8$(_context8) {
      while (1) switch (_context8.prev = _context8.next) {
        case 0:
          return _context8.abrupt("return", new Promise(function (resolve) {
            var delay = 150;
            setTimeoutConfigured(function () {
              resolve(mockAutoCompleteData);
            }, delay);
          }));
        case 1:
        case "end":
          return _context8.stop();
      }
    }, _callee8);
  })));
  mockActionsDiscovery();
  mockActionsExecution(mockExecutionDelay);
};
export var forceBaseUrl = function forceBaseUrl(baseUrl) {
  fetchMock.post(/^\//, function (url, init) {
    return fetch("".concat(baseUrl).concat(url), init);
  });
};
export { ORS_ACTIONS_DISCOVERY_ENDPOINT, mockActionsDiscovery };