'use strict';

exports.__esModule = true;

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; };

exports.default = TutorialEditor;

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

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

var _propTypes2 = _interopRequireDefault(_propTypes);

var _lodash = require('lodash');

var _lodash2 = _interopRequireDefault(_lodash);

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

var _CodeEditor = require('../../../CodeEditor');

var _CodeEditor2 = _interopRequireDefault(_CodeEditor);

var _Method = require('../../../../components/Method');

var _Method2 = _interopRequireDefault(_Method);

var _Menu = require('../../../../components/Menu');

var _Menu2 = _interopRequireDefault(_Menu);

var _Divider = require('../../../../components/Menu/Divider');

var _Divider2 = _interopRequireDefault(_Divider);

var _Header = require('../../../../components/Menu/Header');

var _Header2 = _interopRequireDefault(_Header);

var _Item = require('../../../../components/Menu/Item');

var _Item2 = _interopRequireDefault(_Item);

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

var _styleModule2 = _interopRequireDefault(_styleModule);

var _tutorials = require('../../proptypes/tutorials');

var _apiEndpoints = require('../../proptypes/apiEndpoints');

var _2 = require('../..');

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

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } // 3rd-Party Libraries


// Readme Libs
// import { supportedLanguages } from '@readme/oas-to-snippet';

// Components


// Internals


// Constants


// Permissions


var LanguageDropdown = function LanguageDropdown(_ref) {
  var languageOpts = _ref.languageOpts,
      index = _ref.index,
      props = _objectWithoutProperties(_ref, ['languageOpts', 'index']);

  var maxTabCount = 4;
  var defaultLang = 'c';

  var _useState = (0, _react.useState)(defaultLang),
      language = _useState[0],
      setLanguage = _useState[1];

  var handleTabCreate = function handleTabCreate() {
    if (language) {
      props.handleTabCreate({ language: language });
      setLanguage(defaultLang);
    }
  };

  return _react2.default.createElement(
    _react2.default.Fragment,
    null,
    index < maxTabCount && _react2.default.createElement(
      _components.Dropdown,
      { className: _styleModule2.default['TutorialEditor-Nav-Plus'] },
      _react2.default.createElement(
        _components.Button,
        { bem: { white_text: true } },
        _react2.default.createElement('i', { className: 'fa fa-plus-circle' })
      ),
      _react2.default.createElement(
        _components.Box,
        { bem: [['pop']], style: { padding: 0 } },
        _react2.default.createElement(
          _Menu2.default,
          null,
          _react2.default.createElement(
            _Item2.default,
            { TagName: 'div' },
            _react2.default.createElement(_components.Select, { onChange: function onChange(e) {
                return setLanguage(e.target.value);
              }, options: languageOpts, size: 'sm', value: language })
          ),
          _react2.default.createElement(_Divider2.default, null),
          _react2.default.createElement(
            _Item2.default,
            { color: 'blue', onClick: handleTabCreate },
            'Create Tab'
          )
        )
      )
    )
  );
};

LanguageDropdown.propTypes = process.env.NODE_ENV !== "production" ? {
  handleTabCreate: _propTypes2.default.func,
  index: _propTypes2.default.number,
  languageOpts: _propTypes2.default.arrayOf(_propTypes2.default.shape({
    label: _propTypes2.default.string,
    value: _propTypes2.default.string
  }))
} : {};

var SnippetLanguageMenu = function SnippetLanguageMenu(_ref2) {
  var codeOptions = _ref2.codeOptions,
      languageOpts = _ref2.languageOpts,
      readOnly = _ref2.readOnly,
      setSelectedTab = _ref2.setSelectedTab,
      selectedTab = _ref2.selectedTab,
      props = _objectWithoutProperties(_ref2, ['codeOptions', 'languageOpts', 'readOnly', 'setSelectedTab', 'selectedTab']);

  var handleTabCreate = function handleTabCreate(_ref3) {
    var language = _ref3.language;

    // Basic scaffold for a new tab
    props.handleTabCreate({
      code: '',
      language: language,
      name: '' + language.charAt(0).toUpperCase() + language.slice(1)
    });
  };

  var tutorialTabClasses = function tutorialTabClasses(index) {
    return [_styleModule2.default['TutorialEditor-Nav-Tab'], index === selectedTab && _styleModule2.default['TutorialEditor-Nav-Tab_active']].filter(function (e) {
      return e;
    }).join(' ');
  };

  return _react2.default.createElement(
    _components.Flex,
    null,
    codeOptions && codeOptions.map(function (opt, index) {
      return _react2.default.createElement(
        _components.Button,
        {
          key: index,
          bem: { white_text: true },
          className: '' + tutorialTabClasses(index),
          onClick: function onClick() {
            return setSelectedTab(index);
          }
        },
        opt.name
      );
    }),
    !readOnly && _react2.default.createElement(LanguageDropdown, {
      handleTabCreate: handleTabCreate,
      index: codeOptions.length - 1,
      languageOpts: languageOpts
    })
  );
};

SnippetLanguageMenu.propTypes = process.env.NODE_ENV !== "production" ? {
  codeOptions: _propTypes2.default.arrayOf(_tutorials.CodeOptionProp),
  handleTabCreate: _propTypes2.default.func,
  languageOpts: _propTypes2.default.arrayOf(_propTypes2.default.shape({
    label: _propTypes2.default.string,
    value: _propTypes2.default.string
  })),
  readOnly: _propTypes2.default.bool,
  selectedTab: _propTypes2.default.number,
  setSelectedTab: _propTypes2.default.func
} : {};

var EndpointSelector = function EndpointSelector(_ref4) {
  var baseUrl = _ref4.baseUrl,
      endpoints = _ref4.endpoints,
      codeOptions = _ref4.codeOptions,
      selectedEndpoint = _ref4.selectedEndpoint,
      readOnly = _ref4.readOnly,
      handleSnippetSelection = _ref4.handleSnippetSelection,
      clearSnippetSelection = _ref4.clearSnippetSelection;
  return _react2.default.createElement(
    _components.Dropdown,
    { justify: 'right' },
    _react2.default.createElement(
      _components.Button,
      _extends({
        bem: { white_text: true },
        className: _styleModule2.default['TutorialEditor-Nav-Button'],
        title: selectedEndpoint && selectedEndpoint.title || ''
      }, readOnly && selectedEndpoint && selectedEndpoint.slug && {
        href: baseUrl + '/reference-link/' + selectedEndpoint.slug,
        rel: 'noopener noreferrer',
        target: '_blank'
      }),
      selectedEndpoint && selectedEndpoint.method && _react2.default.createElement(_Method2.default, { type: selectedEndpoint.method.toLowerCase() }),
      _react2.default.createElement(
        'span',
        { className: _styleModule2.default['TutorialEditor-Nav-Button-Text'] },
        selectedEndpoint && selectedEndpoint.title || 'Reference'
      ),
      !readOnly && _react2.default.createElement('i', { className: 'fa fa-chevron-down' }),
      readOnly && selectedEndpoint && selectedEndpoint.slug && _react2.default.createElement('i', { className: ['fa fa-arrow-circle-up', _styleModule2.default['TutorialEditor-Nav-Button-Link-Icon']].join(' ') })
    ),
    !readOnly && _react2.default.createElement(
      _components.Box,
      { bem: [['pop']], className: _styleModule2.default['TutorialEditor-Nav-Menu'] },
      _react2.default.createElement(
        _Menu2.default,
        null,
        selectedEndpoint && selectedEndpoint.title && _react2.default.createElement(
          _react2.default.Fragment,
          null,
          _react2.default.createElement(
            _Header2.default,
            null,
            selectedEndpoint.title
          ),
          _react2.default.createElement(
            _Item2.default,
            { color: 'red', onClick: clearSnippetSelection },
            'Clear Selection'
          ),
          _react2.default.createElement(_Divider2.default, null)
        ),
        _react2.default.createElement(
          _Header2.default,
          null,
          'API Definitions'
        ),
        endpoints && endpoints.map(function (endpoint, index) {
          return _react2.default.createElement(
            _Item2.default,
            { key: 'tutorial-endpoint-group-' + index, openAt: 'left', title: endpoint.title },
            endpoint.title,
            _react2.default.createElement(
              _Menu2.default,
              null,
              _react2.default.createElement(
                _Header2.default,
                null,
                endpoint.title
              ),
              endpoint.children.map(function (child, idx) {
                return _react2.default.createElement(
                  _Item2.default,
                  {
                    key: 'tutorial-endpoint-opt-' + idx,
                    onClick: function onClick() {
                      return handleSnippetSelection({ page: child, codeOptions: codeOptions });
                    },
                    title: child.title
                  },
                  _react2.default.createElement(
                    _react2.default.Fragment,
                    null,
                    _react2.default.createElement(_Method2.default, {
                      className: _styleModule2.default['TutorialEditor-Nav-Menu-Method'],
                      type: child.api.method.toLowerCase(),
                      width: 40
                    }),
                    _react2.default.createElement(
                      'span',
                      { className: _styleModule2.default['TutorialEditor-Nav-Menu-Text'] },
                      child.title
                    )
                  )
                );
              })
            )
          );
        })
      )
    )
  );
};

EndpointSelector.propTypes = process.env.NODE_ENV !== "production" ? {
  baseUrl: _propTypes2.default.string,
  clearSnippetSelection: _propTypes2.default.func,
  codeOptions: _propTypes2.default.arrayOf(_tutorials.CodeOptionProp),
  endpoints: _propTypes2.default.arrayOf(_apiEndpoints.ApiEndpointProp),
  handleSnippetSelection: _propTypes2.default.func,
  readOnly: _propTypes2.default.bool,
  selectedEndpoint: _tutorials.EndpointProp
} : {};

var TabControls = function TabControls(_ref5) {
  var codeOption = _ref5.codeOption,
      selectedLines = _ref5.selectedLines,
      languageOpts = _ref5.languageOpts,
      selectedTab = _ref5.selectedTab,
      isOnlyTab = _ref5.isOnlyTab,
      handleLineUpdate = _ref5.handleLineUpdate,
      handleTabUpdate = _ref5.handleTabUpdate,
      handleTabDelete = _ref5.handleTabDelete;

  var lineNumberRegex = /^[0-9,-]+$/;
  var maxLength = 20;

  var handleLineInput = function handleLineInput(event) {
    var value = event.target.value;


    if (!value || lineNumberRegex.test(value)) {
      handleLineUpdate(value);
    }
  };

  var handleNameInput = function handleNameInput(event, key) {
    var value = event.target.value;

    if (value.length >= maxLength) event.target.value = value.slice(0, maxLength);
    if (value.length > 0) handleTabUpdate(event, key);
  };

  return _react2.default.createElement(
    'div',
    { className: _styleModule2.default['TutorialEditor-Controls'] },
    _react2.default.createElement(
      'label',
      {
        className: [_styleModule2.default['TutorialEditor-Controls-ControlWrapper'], _styleModule2.default['TutorialEditor-Controls-ControlWrapper_select']].join(' ')
      },
      _react2.default.createElement(
        'span',
        null,
        'Language'
      ),
      _react2.default.createElement(
        'select',
        {
          className: _styleModule2.default['TutorialEditor-Controls-ControlWrapper-Select'],
          onChange: function onChange(e) {
            return handleTabUpdate(e, 'language');
          },
          value: codeOption.language
        },
        languageOpts.map(function (_ref6, idx) {
          var value = _ref6.value,
              label = _ref6.label;
          return _react2.default.createElement(
            'option',
            { key: 'tab-control-language-' + idx, value: value },
            label
          );
        })
      )
    ),
    _react2.default.createElement(
      'label',
      { className: _styleModule2.default['TutorialEditor-Controls-ControlWrapper'] },
      _react2.default.createElement(
        'span',
        null,
        'Highlight'
      ),
      _react2.default.createElement('input', {
        className: _styleModule2.default['TutorialEditor-Controls-ControlWrapper-Input'],
        onChange: handleLineInput,
        placeholder: '1,4,7-9',
        value: selectedLines
      }),
      _react2.default.createElement('i', {
        className: ['fa fa-question', _styleModule2.default['TutorialEditor-Controls-ControlWrapper-Tooltip']].join(' '),
        'data-tooltip': 'Highlight multiple lines with commas and hyphens',
        'data-tooltip-position': 'right'
      })
    ),
    _react2.default.createElement(
      'label',
      { className: _styleModule2.default['TutorialEditor-Controls-ControlWrapper'] },
      _react2.default.createElement(
        'span',
        null,
        'Name'
      ),
      _react2.default.createElement('input', {
        className: _styleModule2.default['TutorialEditor-Controls-ControlWrapper-Input'],
        maxLength: maxLength,
        onChange: function onChange(e) {
          return handleNameInput(e, 'name');
        },
        value: codeOption.name
      })
    ),
    _react2.default.createElement(
      'button',
      {
        className: _styleModule2.default['TutorialEditor-Controls-Delete'],
        'data-tooltip': isOnlyTab ? 'Must have at least one tab' : '',
        'data-tooltip-position': 'left',
        disabled: isOnlyTab,
        onClick: function onClick() {
          return handleTabDelete(selectedTab);
        },
        type: 'button'
      },
      'Delete Tab'
    )
  );
};

TabControls.propTypes = process.env.NODE_ENV !== "production" ? {
  codeOption: _tutorials.CodeOptionProp,
  handleLineUpdate: _propTypes2.default.func,
  handleTabDelete: _propTypes2.default.func,
  handleTabUpdate: _propTypes2.default.func,
  isOnlyTab: _propTypes2.default.bool,
  languageOpts: _propTypes2.default.arrayOf(_propTypes2.default.shape({
    label: _propTypes2.default.string,
    value: _propTypes2.default.string
  })),
  selectedLines: _propTypes2.default.string,
  selectedTab: _propTypes2.default.number
} : {};

function TutorialEditor(_ref7) {
  var baseUrl = _ref7.baseUrl,
      snippet = _ref7.snippet,
      endpoints = _ref7.endpoints,
      lineNumbers = _ref7.lineNumbers,
      referenceEnabled = _ref7.referenceEnabled,
      selectedTab = _ref7.selectedTab,
      setSelectedTab = _ref7.setSelectedTab,
      handleSnippetSelection = _ref7.handleSnippetSelection,
      clearSnippetSelection = _ref7.clearSnippetSelection,
      updateStep = _ref7.updateStep,
      updateSnippet = _ref7.updateSnippet,
      props = _objectWithoutProperties(_ref7, ['baseUrl', 'snippet', 'endpoints', 'lineNumbers', 'referenceEnabled', 'selectedTab', 'setSelectedTab', 'handleSnippetSelection', 'clearSnippetSelection', 'updateStep', 'updateSnippet']);

  var _useState2 = (0, _react.useState)(null),
      editorInstance = _useState2[0],
      setEditorInstance = _useState2[1];

  var _useState3 = (0, _react.useState)(''),
      setLineNumbers = _useState3[1];

  var codeOptions = snippet.codeOptions,
      endpoint = snippet.endpoint;

  // TODO resolve module build issues for @readme/oas-to-snippet

  var languageOpts = [{ value: 'c', label: 'c' }, { value: 'node', label: 'node' }, { value: 'shell', label: 'curl' }, { value: 'python', label: 'python' }, { value: 'php', label: 'php' }];
  // const languageOpts = Object.keys(supportedLanguages).map(key => {
  //   return { value: key, label: key };
  // });

  // Converting between human readable `1, 2-5` to codemirror selection syntax
  var spreadLineNumbers = function spreadLineNumbers(ranges) {
    return ranges.split(',').map(function (range) {
      var _range$split = range.split('-'),
          anchor = _range$split[0],
          head = _range$split[1];

      var end = head || anchor ? parseInt(head || anchor, 10) : 0;
      var start = parseInt(anchor || 0, 10) - 1;

      return [{ ch: 0, line: start }, { ch: 0, line: end }];
    });
  };
  // Get the defined dimensions based on the first selected range
  // to programmatically scroll. This is necessary because codemirror likes to put
  // a margin buffer in their component
  var getEditorDimensions = function getEditorDimensions(editor, range) {
    var editorHeight = editor.getWrapperElement().parentNode.parentNode.offsetHeight;
    var lineHeight = 15;
    var start = range[0],
        end = range[1];


    var rangeHeight = (end.line - start.line) * lineHeight;
    var editorCenter = start.line * lineHeight - editorHeight / 2 - lineHeight / 2;

    // if there’s a range greater than one line
    if (rangeHeight > 15) {
      editorCenter += rangeHeight / 2;
      // if the range is larger than the editor
      if (rangeHeight > editorHeight) editorCenter = start.line * lineHeight - lineHeight;
    }

    return { editorHeight: editorHeight, editorCenter: editorCenter };
  };

  var markEditorInstance = function markEditorInstance(editor, lines) {
    // Clear existing style tags from our editor instance
    editor.getAllMarks().forEach(function (mark) {
      return mark.clear();
    });

    if (lines) {
      var ranges = spreadLineNumbers(lines);
      // Mark new ranges with classname
      ranges.forEach(function (_ref8) {
        var anchor = _ref8[0],
            head = _ref8[1];
        return editor.getDoc().markText(anchor, head, { className: 'CodeEditor-Highlight', addToHistory: true });
      });
      // Scroll to the first range so that code is in viewport

      var _getEditorDimensions = getEditorDimensions(editor, ranges[0]),
          editorHeight = _getEditorDimensions.editorHeight,
          editorCenter = _getEditorDimensions.editorCenter;

      editor.setSize('100%', editorHeight);
      editor.scrollTo(0, editorCenter);
    }
  };

  // Editor user interaction marking
  // Called when lineNumbers is updated (via input or step/tab change)
  (0, _react.useEffect)(function () {
    var newLines = lineNumbers[selectedTab];
    if (editorInstance) {
      setLineNumbers(function (prevLines) {
        if (newLines === prevLines) return prevLines;
        setTimeout(function () {
          return markEditorInstance(editorInstance, newLines);
        });
        return newLines;
      });
    }
  });

  // getCode() is called when two conditions are fulfilled:
  // 1. When a snippet is already selected and assigned to the tutorial and a new tab is created
  // 2. When we create a new step
  // getCode will retrieve a code string and place it within the tab's target index
  var getCode = function getCode(language, index) {
    var page = snippet.endpoint.page;

    var pages = endpoints.reduce(function (arr, val) {
      return arr.concat(val.children);
    }, []);
    var foundPage = pages.find(function (_ref9) {
      var _id = _ref9._id;
      return _id === page;
    });

    if (foundPage) props.getCode({ page: foundPage, language: language, index: index });
  };

  var handleTabCreate = function handleTabCreate(codeOption) {
    lineNumbers.push('');
    updateStep({ lineNumbers: lineNumbers });

    codeOptions.push(codeOption);
    updateSnippet({ codeOptions: codeOptions });

    setSelectedTab(codeOptions.length - 1);
    getCode(codeOption.language, snippet.codeOptions.length - 1);
  };

  var handleTabUpdate = function handleTabUpdate(event, key) {
    codeOptions[selectedTab][key] = event.target.value;
    updateSnippet({ codeOptions: codeOptions });
  };

  var handleTabDelete = function handleTabDelete(index) {
    lineNumbers.splice(index, 1);
    updateStep({ lineNumbers: lineNumbers });

    codeOptions.splice(index, 1);
    updateSnippet({ codeOptions: codeOptions });

    setSelectedTab(0);
  };

  var handleLineUpdate = function handleLineUpdate(value) {
    lineNumbers[selectedTab] = value;
    updateStep({ lineNumbers: lineNumbers });
  };

  var handleCodeChange = function handleCodeChange(_ref10, code, readOnly) {
    var origin = _ref10.origin;

    if (['+input', 'paste', '+delete'].includes(origin) && !readOnly) {
      codeOptions[selectedTab].code = code;
      updateSnippet({ codeOptions: codeOptions });
    }
  };

  var checkCodeChange = process.env.NODE_ENV === 'test' ? handleCodeChange : _lodash2.default.debounce(handleCodeChange, 300);

  return _react2.default.createElement(
    _2.PermissionContext.Consumer,
    null,
    function (readOnly) {
      return _react2.default.createElement(
        _react2.default.Fragment,
        null,
        _react2.default.createElement(
          _components.Flex,
          { align: 'center', className: _styleModule2.default['TutorialEditor-Nav'], justify: 'between', tag: 'nav' },
          _react2.default.createElement(SnippetLanguageMenu, {
            codeOptions: codeOptions,
            handleTabCreate: handleTabCreate,
            languageOpts: languageOpts,
            readOnly: readOnly,
            selectedTab: selectedTab,
            setSelectedTab: setSelectedTab
          }),
          referenceEnabled && (readOnly || endpoints.length > 0) && _react2.default.createElement(EndpointSelector, {
            baseUrl: baseUrl,
            clearSnippetSelection: clearSnippetSelection,
            codeOptions: snippet.codeOptions,
            endpoints: endpoints,
            handleSnippetSelection: handleSnippetSelection,
            readOnly: readOnly,
            selectedEndpoint: endpoint
          })
        ),
        _react2.default.createElement(_CodeEditor2.default, {
          autoScroll: true,
          className: 'CodeEditor-Input ' + (readOnly && 'CodeEditor-Input_readonly' || ''),
          code: codeOptions[selectedTab].code,
          editorDidMount: setEditorInstance,
          lang: codeOptions[selectedTab].language,
          onChange: function onChange(editor, data, code) {
            return checkCodeChange(data, code, readOnly);
          },
          options: { readOnly: readOnly ? 'nocursor' : false }
        }),
        !readOnly && _react2.default.createElement(TabControls, {
          codeOption: codeOptions[selectedTab],
          handleLineUpdate: handleLineUpdate,
          handleTabDelete: handleTabDelete,
          handleTabUpdate: handleTabUpdate,
          isOnlyTab: codeOptions.length === 1,
          languageOpts: languageOpts,
          selectedLines: lineNumbers[selectedTab],
          selectedTab: selectedTab
        })
      );
    }
  );
}

TutorialEditor.propTypes = process.env.NODE_ENV !== "production" ? {
  baseUrl: _propTypes2.default.string,
  clearSnippetSelection: _propTypes2.default.func,
  endpoints: _propTypes2.default.arrayOf(_apiEndpoints.ApiEndpointProp),
  getCode: _propTypes2.default.func,
  handleSnippetSelection: _propTypes2.default.func,
  lineNumbers: _propTypes2.default.arrayOf(_propTypes2.default.string),
  referenceEnabled: _propTypes2.default.bool,
  selectedTab: _propTypes2.default.number,
  setSelectedTab: _propTypes2.default.func,
  snippet: _tutorials.StepSnippetProp,
  updateSnippet: _propTypes2.default.func,
  updateStep: _propTypes2.default.func
} : {};
module.exports = exports['default'];