'use strict';

exports.__esModule = true;
exports.PermissionContext = undefined;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; // 3rd-party libs


// Internals


// Components


// Constants


// Style


exports.default = Tutorials;

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

var _cloneDeep = require('lodash/cloneDeep');

var _cloneDeep2 = _interopRequireDefault(_cloneDeep);

var _apiActions = require('./apiActions');

var ApiActions = _interopRequireWildcard(_apiActions);

var _useReadmeApi2 = require('../../core/hooks/useReadmeApi');

var _useReadmeApi3 = _interopRequireDefault(_useReadmeApi2);

var _components = require('../../ui/components');

var _TutorialHero = require('./components/TutorialHero');

var _TutorialHero2 = _interopRequireDefault(_TutorialHero);

var _TutorialCard = require('../../ui/compositions/TutorialCard');

var _TutorialCard2 = _interopRequireDefault(_TutorialCard);

var _TutorialModal = require('../../ui/compositions/TutorialModal');

var _TutorialModal2 = _interopRequireDefault(_TutorialModal);

var _TutorialObstacle = require('../../ui/compositions/TutorialObstacle');

var _TutorialObstacle2 = _interopRequireDefault(_TutorialObstacle);

var _stepDefaults = require('../../ui/compositions/TutorialModal/constants/stepDefaults');

var _styleModule = require('./style.module.scss');

var _styleModule2 = _interopRequireDefault(_styleModule);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PermissionContext = exports.PermissionContext = _react2.default.createContext(false);

function Tutorials(props) {
  var baseUrl = props.baseUrl,
      modalTarget = props.modalTarget,
      slug = props.slug,
      referenceEnabled = props.referenceEnabled;

  var _useState = (0, _react.useState)({}),
      hero = _useState[0],
      setHero = _useState[1];

  var _useState2 = (0, _react.useState)({}),
      onboarding = _useState2[0],
      setOnboarding = _useState2[1];

  var _useState3 = (0, _react.useState)([]),
      tutorials = _useState3[0],
      setTutorials = _useState3[1];

  var _useState4 = (0, _react.useState)(true),
      initialLoad = _useState4[0],
      setInitialLoad = _useState4[1];

  var _useState5 = (0, _react.useState)({
    open: false,
    action: 'View'
  }),
      modalMeta = _useState5[0],
      setModalMeta = _useState5[1];

  var _useState6 = (0, _react.useState)(false),
      moduleEnabled = _useState6[0],
      setModuleEnabled = _useState6[1];

  var _useState7 = (0, _react.useState)(),
      selectedTutorial = _useState7[0],
      setSelectedTutorial = _useState7[1];

  var _useState8 = (0, _react.useState)(props.isAdmin),
      isAdmin = _useState8[0];

  var _useReadmeApi = (0, _useReadmeApi3.default)(baseUrl),
      response = _useReadmeApi.response,
      error = _useReadmeApi.error,
      setError = _useReadmeApi.setError,
      pendingRequest = _useReadmeApi.pendingRequest,
      initRequest = _useReadmeApi.initRequest;

  var getTutorials = function getTutorials() {
    return ApiActions.getTutorials(initRequest);
  };

  (0, _react.useEffect)(function () {
    getTutorials();
  }, []);

  (0, _react.useEffect)(function () {
    if (pendingRequest) getTutorials();
  }, [pendingRequest]);

  (0, _react.useEffect)(function () {
    if (Object.keys(response).length) setInitialLoad(false);
  }, [response]);

  (0, _react.useEffect)(function () {
    if (response.hero) setHero(response.hero);
  }, [response.hero]);

  (0, _react.useEffect)(function () {
    if (response.tutorialOnboarding) setOnboarding(response.tutorialOnboarding);
  }, [response.tutorialOnboarding]);

  (0, _react.useEffect)(function () {
    if (response.tutorials) setTutorials(response.tutorials);
  }, [response.tutorials]);

  (0, _react.useEffect)(function () {
    if ('moduleEnabled' in response) setModuleEnabled(response.moduleEnabled);
  }, [response.moduleEnabled]);

  (0, _react.useEffect)(function () {
    if (slug) {
      ApiActions.getTutorialBySlug(initRequest, { slug: slug });
      setTimeout(function () {
        return getTutorials();
      });
    }
  }, [slug]);

  (0, _react.useEffect)(function () {
    if (response.tutorial && !response.tutorialPublishToggled) {
      setSelectedTutorial(response.tutorial);
      setModalMeta({
        open: true,
        action: 'View'
      });
    }
  }, [response.tutorial]);

  var pushState = function pushState(pathSlug) {
    var urlRegexp = /https?:\/\//;
    if (!urlRegexp.test(baseUrl)) {
      var uri = pathSlug ? baseUrl + '/tutorials/' + pathSlug : baseUrl + '/tutorials';
      // eslint-disable-next-line no-restricted-globals
      history.pushState('', '', uri);
    }
  };

  var openTutorial = function openTutorial(action, id) {
    setModalMeta({
      open: true,
      action: action
    });
    // Allow us to differentiate based on two factors
    // What type of modal action is this? View|Create|Update
    // And is this the first time we're opening it?
    setSelectedTutorial(function (prevTutorial) {
      var prevId = prevTutorial && prevTutorial._id && prevTutorial._id.toString();
      var newId = id && id.toString() || '';

      if (prevId !== newId && action === 'Create') {
        return _extends({}, (0, _cloneDeep2.default)(_stepDefaults.DEFAULT_TUTORIAL));
      } else if (prevId !== newId) {
        var tutorial = tutorials.find(function (tut) {
          return tut._id.toString() === newId;
        });
        pushState(tutorial.slug);
        return _extends({}, tutorial);
      }
      // If we're opening the same modal, we don't want to overwrite any previous work
      return prevTutorial;
    });
  };

  var closeTutorialModal = function closeTutorialModal() {
    pushState();
    setModalMeta(function (prevMeta) {
      return _extends({}, prevMeta, {
        open: false
      });
    });
  };

  return _react2.default.createElement(
    PermissionContext.Provider,
    { value: isAdmin },
    !initialLoad && !tutorials.length && _react2.default.createElement(
      _TutorialObstacle2.default,
      {
        body: 'Tutorials are task-driven guidance for your API. Try creating a new Tutorial for your users!',
        className: modalMeta.open && 'paused',
        heading: 'Create a Tutorial to Get Started'
      },
      _react2.default.createElement(
        _components.Button,
        { onClick: function onClick() {
            return openTutorial('Create');
          } },
        'Create Tutorial'
      ),
      _react2.default.createElement(
        _components.Button,
        { bem: { shale: true } },
        'Try Example'
      )
    ),
    tutorials.length > 0 && _react2.default.createElement(
      _react2.default.Fragment,
      null,
      hero && hero.title && _react2.default.createElement(_TutorialHero2.default, { hero: hero, openTutorial: openTutorial }),
      _react2.default.createElement(
        'section',
        { className: _styleModule2.default.TutorialGrid },
        tutorials.map(function (tutorial, idx) {
          return _react2.default.createElement(_TutorialCard2.default, {
            key: 'tut-' + idx,
            className: _styleModule2.default['TutorialGrid-Card'],
            deleteTutorial: function deleteTutorial(e) {
              return ApiActions.deleteTutorial(initRequest, e);
            },
            makeHero: function makeHero(e) {
              return ApiActions.makeHero(initRequest, e);
            },
            numTutorials: tutorials.length,
            openTutorial: openTutorial,
            shiftOrder: function shiftOrder(e) {
              return ApiActions.shiftOrder(initRequest, e);
            },
            tutorial: tutorial,
            updateTutorial: function updateTutorial(e) {
              return ApiActions.updateTutorial(initRequest, e);
            }
          });
        })
      )
    ),
    isAdmin && _react2.default.createElement(
      'div',
      { className: _styleModule2.default.TutorialToolbar },
      _react2.default.createElement(
        'div',
        {
          'data-tooltip': !tutorials.length ? 'The Tutorial view won’t be shown until you create your first tutorial.' : '',
          'data-tooltip-position': 'top'
        },
        _react2.default.createElement(_components.Toggle, {
          checked: moduleEnabled,
          disabled: !tutorials.length,
          label: 'Show Tutorials in Navigation',
          onChange: function onChange() {
            return ApiActions.toggleModule(initRequest);
          },
          type: 'toggle'
        })
      ),
      _react2.default.createElement(
        _components.Button,
        {
          bem: { blue: true },
          circular: true,
          className: _styleModule2.default['TutorialToolbar-Button'],
          onClick: function onClick() {
            return openTutorial('Create');
          }
        },
        'Create Tutorial'
      )
    ),
    isAdmin && error && _react2.default.createElement(
      _components.Notification,
      { color: 'red', dismissible: true, handleClick: function handleClick() {
          return setError(null);
        }, position: 'top' },
      _react2.default.createElement(
        'p',
        null,
        error
      )
    ),
    _react2.default.createElement(_TutorialModal2.default, {
      action: modalMeta.action,
      baseUrl: baseUrl,
      closeTutorialModal: closeTutorialModal,
      endpointOnboarding: onboarding.endpoints,
      open: modalMeta.open,
      referenceEnabled: referenceEnabled,
      requestDataRefresh: function requestDataRefresh() {
        return getTutorials();
      },
      target: modalTarget,
      tutorial: selectedTutorial
    })
  );
}

Tutorials.propTypes = process.env.NODE_ENV !== "production" ? {
  baseUrl: _propTypes2.default.string,
  isAdmin: _propTypes2.default.bool.isRequired,
  modalTarget: _propTypes2.default.string,
  referenceEnabled: _propTypes2.default.bool,
  slug: _propTypes2.default.string
} : {};

Tutorials.defaultProps = {
  baseUrl: '',
  isAdmin: false,
  modalTarget: '#modal-root',
  referenceEnabled: false
};