"use strict";

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));

var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));

var _react = _interopRequireDefault(require("react"));

var _enzyme = require("enzyme");

var _reactHooks = require("@testing-library/react-hooks");

require("isomorphic-fetch");

var _fetchMock = _interopRequireDefault(require("fetch-mock"));

var _ = _interopRequireDefault(require("."));

var _components = require("../../../components");

var _TutorialStep = _interopRequireDefault(require("./components/TutorialStep"));

var _TutorialStepNav = _interopRequireDefault(require("./components/TutorialStepNav"));

var _TutorialEditor = _interopRequireDefault(require("./components/TutorialEditor"));

var _TutorialResponse = _interopRequireDefault(require("./components/TutorialResponse"));

var _useReadmeApi = _interopRequireDefault(require("../../../../core/hooks/useReadmeApi"));

var ApiActions = _interopRequireWildcard(require("./apiActions"));

var _stepDefaults = require("./constants/stepDefaults");

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { (0, _defineProperty2["default"])(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

// Mocking
var getClientRectSpy = jest.fn(function () {
  return {
    width: 100
  };
});
Range.prototype.getBoundingClientRect = getClientRectSpy;
Range.prototype.getClientRects = getClientRectSpy;

window.HTMLElement.prototype.scroll = function () {};

describe('TutorialModal', function () {
  var _renderHook = (0, _reactHooks.renderHook)(function () {
    return (0, _useReadmeApi["default"])('http://localhost:3000');
  }),
      result = _renderHook.result;

  beforeAll( /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2() {
    return _regenerator["default"].wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            _fetchMock["default"].get('http://localhost:3000/tutorials/endpoints', {
              endpoints: [{
                title: '/pets',
                children: [{
                  _id: '123',
                  api: {
                    apiSetting: '22',
                    method: 'GET'
                  },
                  slug: 'getPets'
                }]
              }]
            });

            _context2.next = 3;
            return (0, _reactHooks.act)( /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() {
              var initRequest;
              return _regenerator["default"].wrap(function _callee$(_context) {
                while (1) {
                  switch (_context.prev = _context.next) {
                    case 0:
                      initRequest = result.current.initRequest;
                      _context.next = 3;
                      return initRequest({
                        method: 'GET',
                        path: 'tutorials/endpoints'
                      });

                    case 3:
                    case "end":
                      return _context.stop();
                  }
                }
              }, _callee);
            })));

          case 3:
          case "end":
            return _context2.stop();
        }
      }
    }, _callee2);
  })));
  describe('Admin actions', function () {
    var node;
    var props;
    beforeEach(function () {
      props = {
        action: 'Create',
        baseUrl: 'http://localhost:3000',
        closeTutorialModal: jest.fn(),
        open: true,
        target: 'body',
        tutorial: _objectSpread(_objectSpread({}, _stepDefaults.DEFAULT_TUTORIAL), {}, {
          steps: [{
            title: 'Step One',
            body: 'Step one body',
            isOpen: true,
            lineNumbers: ['1-3']
          }, {
            title: 'Step Two',
            body: 'step two body',
            isOpen: false,
            lineNumbers: ['']
          }]
        })
      };
      node = (0, _enzyme.mount)( /*#__PURE__*/_react["default"].createElement(_["default"], props));
    });
    describe('Step Actions', function () {
      it('should select a step', function () {
        var section = node.find(_TutorialStep["default"]).at(1).find('section');
        section.simulate('click');
        var step = node.find(_TutorialStep["default"]).at(1);
        expect(step.prop('step').isOpen).toStrictEqual(true);
      });
      describe('Step Operations', function () {
        it('should shift step up on up button click', function () {
          var shiftButton = node.find(_TutorialStep["default"]).at(1).find(_components.Button).at(0);
          shiftButton.simulate('click');
          var step = node.find(_TutorialStep["default"]).at(1);
          expect(step.prop('step')).toStrictEqual(props.tutorial.steps[0]);
        });
        it('should create a step', function () {
          var createStep = node.find(_TutorialStepNav["default"]).find('.TutorialStepNav-Button').at(0);
          createStep.simulate('click');
          var step = node.find(_TutorialStep["default"]).at(2);
          expect(step).not.toBeUndefined();
        });
        it('should update a step', function () {
          var stepInput = node.find('.TutorialStep').find(_components.Input).find('.Input').at(0);
          var event = {
            target: {
              value: 'New Title',
              id: 'tutorialStep-title-status'
            }
          };
          stepInput.simulate('change', event);
          var step = node.find(_TutorialStep["default"]).at(0);
          expect(step.prop('step').title).toStrictEqual('New Title');
        });
        it('should delete a step', function () {
          var deleteButton = node.find(_TutorialStepNav["default"]).find('.TutorialStep-Header-Button_red').at(0);
          deleteButton.simulate('click');
          var steps = node.find(_TutorialStep["default"]);
          expect(steps).toHaveLength(1);
        });
      });
    });
    describe('Snippet Actions', function () {
      it('should clear snippet selection', function () {
        var prop2 = {
          action: 'Edit',
          baseUrl: 'http://localhost:3000',
          closeTutorialModal: jest.fn(),
          open: true,
          target: 'body',
          tutorial: _objectSpread(_objectSpread({}, _stepDefaults.DEFAULT_TUTORIAL), {}, {
            snippet: {
              endpoint: {
                page: '123',
                method: 'GET',
                slug: 'getPets',
                title: '/pets'
              },
              codeOptions: [{
                code: 'Hello world!',
                language: 'node',
                name: 'Node'
              }]
            }
          })
        };
        var node2 = (0, _enzyme.mount)( /*#__PURE__*/_react["default"].createElement(_["default"], prop2));
        var editor = node2.find(_TutorialEditor["default"]);
        editor.prop('clearSnippetSelection')();
        setTimeout(function () {
          var editorRef = node2.find(_TutorialEditor["default"]);
          expect(editorRef.prop('snippet').endpoint.apiSetting).toBeUndefined();
        });
      });
      describe('Snippet Operations', function () {
        it('should update snippet when tab is edited', function () {
          var tabInput = node.find(_TutorialEditor["default"]).find('.TutorialEditor-Controls').find('.TutorialEditor-Controls-ControlWrapper').find('.TutorialEditor-Controls-ControlWrapper-Input').at(1);
          var event = {
            target: {
              value: 'codeName'
            }
          };
          tabInput.simulate('change', event);
          var editor = node.find(_TutorialEditor["default"]);
          expect(editor.props().snippet.codeOptions[0].name).toStrictEqual('codeName');
        });
        it('should rerender when the response is changed', function () {
          var responseInput = node.find(_TutorialResponse["default"]).find('.CodeEditor').first();
          var responseProps = responseInput.props();
          responseProps.onChange(responseProps, {
            origin: '+input'
          }, 'hello');
          var editor = node.find(_TutorialResponse["default"]);
          expect(editor.props().response.length).toBeGreaterThan(0);
        });
      });
      describe('Tutorial Operations', function () {
        it('should call `ApiActions.createTutorial` when draft is saved', function () {
          _fetchMock["default"].post('http://localhost:3000/tutorials', {
            tutorial: {
              snippet: _stepDefaults.DEFAULT_SNIPPET
            }
          });

          var button = node.find('button').at(2);
          var spy = jest.spyOn(ApiActions, 'createTutorial');
          button.simulate('click');
          expect(spy).toHaveBeenCalledTimes(1);
        });
        it('should call `ApiActions.updateTutorial` when saved with _id', function () {
          var p2 = {
            action: 'Create',
            baseUrl: 'http://localhost:3000',
            closeTutorialModal: jest.fn(),
            open: true,
            target: 'body',
            tutorial: _objectSpread(_objectSpread({}, _stepDefaults.DEFAULT_TUTORIAL), {}, {
              _id: '123',
              steps: [{
                title: 'Step One',
                body: 'Step one body',
                isOpen: true,
                lineNumbers: ['1-3']
              }]
            })
          };
          var n2 = (0, _enzyme.mount)( /*#__PURE__*/_react["default"].createElement(_["default"], p2));

          _fetchMock["default"].put('http://localhost:3000/tutorials/123', {
            tutorial: {
              snippet: _stepDefaults.DEFAULT_SNIPPET
            }
          });

          var button = n2.find('button').at(2);
          var spy = jest.spyOn(ApiActions, 'updateTutorial');
          button.simulate('click');
          expect(spy).toHaveBeenCalledTimes(1);
        });
      });
    });
  });
  describe('Readonly actions', function () {
    var node;
    var props;
    beforeEach(function () {
      props = {
        action: 'View',
        baseUrl: 'http://localhost:3000',
        closeTutorialModal: jest.fn(),
        open: true,
        target: 'body',
        tutorial: _objectSpread(_objectSpread({}, _stepDefaults.DEFAULT_TUTORIAL), {}, {
          steps: [{
            title: 'Step One',
            body: 'Step one body',
            isOpen: true,
            lineNumbers: ['1-3']
          }, {
            title: 'Step Two',
            body: 'step two body',
            isOpen: false,
            lineNumbers: ['']
          }]
        })
      };
      node = (0, _enzyme.mount)( /*#__PURE__*/_react["default"].createElement(_["default"], props));
    });
    it('should display a modal', function () {
      expect(node.find(_components.Modal)).toHaveLength(1);
    });
    it('should navigate between steps', function () {
      var button = node.find(_TutorialStep["default"]).at(0).find('footer').find('button').at(0);
      button.simulate('click');
      var step = node.find(_TutorialStep["default"]).at(0);
      expect(step.prop('step').isOpen).toStrictEqual(false);
    });
  });
  describe('Review', function () {
    var node;
    var props;
    beforeEach(function () {
      props = {
        action: 'Create',
        baseUrl: 'http://localhost:3000',
        closeTutorialModal: jest.fn(),
        open: true,
        target: 'body',
        tutorial: _objectSpread(_objectSpread({}, _stepDefaults.DEFAULT_TUTORIAL), {}, {
          steps: [{
            title: 'Step One',
            body: 'Step one body',
            isOpen: true,
            lineNumbers: ['1-3']
          }]
        })
      };
      node = (0, _enzyme.mount)( /*#__PURE__*/_react["default"].createElement(_["default"], props));
      var trigger = node.find('button').at(1);
      trigger.simulate('click');
    });
    it('should display the review pane', function () {
      expect(node.find('.TutorialModal-Nav-Tab_active').text()).toContain('Appearance');
    });
  });
});