const getContentFromForm = async (uuid, parentContainer) => {
  const container = $('<div>', {style: 'width: 100%; overflow: hidden;'});
  if(parentContainer) {
    container.css('height', '100%');
  } else {
    container.css('height', 'calc(100% - 40px)');
  }

  let editable = false;
  const buttonsPanel = $('<div>', {class: 'wf-form-buttons-panel'});
  const playerContainer = $('<div>', {class: 'wf-form-player-container'});
  const player = UTILS.getSynergyPlayer(uuid, false);
  const buttonSave = $('<span class="material-icons wf-icons" style="display: none;">save</span>');
  const buttonPrint = $('<span class="material-icons wf-icons">print</span>');
  const buttonEditable = $('<span class="material-icons wf-icons">edit</span>');


  player.view.container.css({'background': '#fff'});
  playerContainer.append(player.view.container);

  buttonSave.on('click', e => {
    if(!player.model.hasChanges) return;
    Cons.showLoader();
    if(!player.model.isValid()) {
      showMessage(i18n.tr('Заполните обязательные поля'), 'error');
      Cons.hideLoader();
    } else {
      player.saveFormData(result => {
        showMessage(i18n.tr('Данные сохранены'), 'success');
        Cons.hideLoader();
      });
    }
  });

  buttonPrint.on('click', e => {
    if(player.model.hasPrintable) {
      window.open(`../Synergy/rest/asforms/template/print/form?format=pdf&dataUUID=${uuid}`);
    } else {
      UTILS.printForm(player.view.container[0]);
    }
  });

  buttonEditable.on('click', e => {
    editable = !editable;
    player.view.setEditable(editable);
    if(editable) {
      buttonEditable.text('description');
      buttonPrint.hide();
      buttonSave.show();
    } else {
      buttonEditable.text('edit');
      buttonPrint.show();
      if(player.model.hasChanges) {
        buttonSave.show();
      } else {
        buttonSave.hide();
      }
    }
  });

  buttonsPanel.append(
    $('<div>').append(buttonSave, buttonPrint),
    $('<div>').append(buttonEditable)
  );

  container.append(buttonsPanel, playerContainer);
  return {container, player};
}

this.openFormPlayer = async (uuid, parentContainer = null, closeDialogHandler) => {
  Cons.showLoader();
  const {container: body, player} = await getContentFromForm(uuid, parentContainer);
  const meaning = await appAPI.getDocMeaningContent(uuid) || 'Документ';

  if(parentContainer) {
    parentContainer.empty();
    parentContainer.append(body);
  } else {
    const dialog = UTILS.getFullModalDialog(meaning, body);
    UIkit.modal(dialog).show();
    dialog.on('hidden', () => {
      dialog.remove();
      if(closeDialogHandler && player.model.hasChanges) closeDialogHandler();
    });
  }
  Cons.hideLoader();
}
