(function ($, Drupal) {

  var tabIdentifier = sessionStorage.tabId && sessionStorage.closedLastTab !== '2' ? sessionStorage.tabId : sessionStorage.tabId = Math.round(10000000 * Math.random()) + Date.now().toString();
  var nodeId = window.drupalSettings.path.nid;

  $(document).ready(function (e) {

    sessionStorage.closedLastTab = '2';

    var promises = [];
    var messages = new Drupal.Message();

    var promise_outer = $.Deferred();
    promises.push(promise_outer);

    var promise_lock = Drupal.restconsumer.patch('/pagedesigner/lock/' + nodeId, { identifier: tabIdentifier });
    promise_lock.done(function ($result) {
      if ($result[0] === true) {
        promise_outer.resolve();
        $(document).on('submit', '#page-settings form', function (e) {
          e.preventDefault();
          const openSettings = editor.Panels.getButton('sidebar', 'sidebar-open-settings');
          openSettings && openSettings.set('active', false);
          Drupal.restconsumer.submit($(this), {}, '', {
            success: function () { return true; },
            complete: function () { return true; }
          }).done(function () {
            document.getElementById('page-settings').innerHTML = '';
            const settings_form = document.createElement('div');
            settings_form.id = 'page-settings-form';
            document.getElementById('page-settings').appendChild(settings_form);
            Drupal.ajax({ url: '/node/' + nodeId + '/edit', wrapper: 'page-settings-form' }).execute();
          });
        });
      } else {
        promise_outer.reject();
        $('body').removeClass('pd-editing-mode');
        $('#pagedesigner-loading-screen-container').fadeOut(300, function () {
          $(this).remove();
        });
        if ($result[1] == 'different identifier') {
          messages.add(Drupal.t('This page is currently being edited by you in another tab. Continue editing in that tab or close the other tab and reload here.'), { type: 'warning' });
        }
      }
    });

    var promise_patterns = Drupal.restconsumer.get('/pagedesigner/pattern');
    promises.push(promise_patterns);
    promise_patterns.done(function (patterns) {
      window.grapes_plugins = [];
      window.grapes_plugins.push('grapesjs-parser-postcss');
      window.patterns = patterns;
    });

    promise_patterns.fail(function () {
      messages.add(Drupal.t('An internal error has occurred, but it might be only temporary. Please refresh the page to try again.'), {type: 'warning'});
      $('#pagedesigner-loading-screen-container').fadeOut(300, function () {
        $(this).remove();
      });
    });

    $.when(...promises).done(function() {
      initPDGrapes(window.patterns, tabIdentifier);
    })

  });

  $(window).on('beforeunload', function () {
    sessionStorage.closedLastTab = '1';
    Drupal.restconsumer.delete('/pagedesigner/lock/' + nodeId, { identifier: tabIdentifier });
  });

})(jQuery, Drupal);
