'use strict';
var __importDefault =
  (this && this.__importDefault) ||
  function (mod) {
    return mod && mod.__esModule ? mod : { default: mod };
  };
Object.defineProperty(exports, '__esModule', { value: true });
const styleNames_1 = __importDefault(require('../../../styleNames'));
const utils_1 = require('../../../utils');
const createConfigPage_1 = require('../createConfigPage');
const helpers_1 = require('./helpers');
const options = [
  { name: 'текст', value: 'text', selected: true },
  { name: 'целое число', value: 'integer' },
  { name: 'дробное число', value: 'float' },
  { name: 'логическое значение', value: 'checkbox' },
  { name: 'список вариантов', value: 'select' },
  { name: 'раздел', value: 'details' },
];
let isCreatedSection = false;
let newSection;
let oldValues;
let targetNode;
const createForm = (props) => {
  oldValues = props.oldValues;
  targetNode = props.targetNode;
  if (!oldValues) {
    targetNode.open = true;
  }
  const form = (0, utils_1.createElement)('form', {
    className: styleNames_1.default.form,
  });
  window.setTimeout(() => document.addEventListener('click', removeForm));
  const nameInput = createInput(
    'Имя поля',
    (oldValues === null || oldValues === void 0 ? void 0 : oldValues.name) || '',
    styleNames_1.default.formNameInput,
    form,
  );
  window.setTimeout(() => nameInput.focus());
  createInput(
    'Ключ поля',
    (oldValues === null || oldValues === void 0 ? void 0 : oldValues.key) || '',
    styleNames_1.default.formKeyInput,
    form,
  );
  const valueTypeInputWrapper = (0, utils_1.createElement)('div', null, form);
  (0, utils_1.createElement)(
    'span',
    { innerHTML: 'Тип значения:' },
    valueTypeInputWrapper,
  );
  const valueInputTypeSelect = (0, utils_1.createElement)(
    'select',
    { className: styleNames_1.default.formValueTypeInput },
    valueTypeInputWrapper,
    options.map((opt) =>
      (0, utils_1.createElement)('option', {
        innerHTML: opt.name,
        id: `c_opt_${opt.value}`,
        value: opt.value,
        selected: opt.selected,
      }),
    ),
  );
  let valueInputType,
    valueInput = createInput(
      'Значение поля',
      '',
      styleNames_1.default.formValueInput,
      form,
    );
  valueInputTypeSelect.onchange = (e) => {
    var _a, _b;
    const valueInputTypeSelect = e.target;
    const valueInputType = valueInputTypeSelect.value;
    let newValueInput;
    (_b =
      (_a = form.querySelector(`.${styleNames_1.default.formStepInput}`)) === null ||
      _a === void 0
        ? void 0
        : _a.parentElement) === null || _b === void 0
      ? void 0
      : _b.remove();
    if (!newSection) {
      isCreatedSection = valueInputType === 'details';
    } else {
      if (valueInputType !== 'details') {
        newSection = null;
        isCreatedSection = false;
      }
    }
    switch (valueInputType) {
      case 'select': {
        newValueInput = createOptionsForm([]);
        break;
      }
      case 'details': {
        newValueInput = (0, utils_1.createElement)('div', {
          innerHTML:
            'Вы перейдёте к созданию дочернего поля,<br /> как только завершите создание текущего.',
        });
        break;
      }
      case 'float':
      case 'integer': {
        newValueInput = (0, utils_1.createElement)('input', {
          type: 'number',
          className: styleNames_1.default.formValueInput,
          required: true,
          step: valueInputType === 'float' ? '0.1' : '1',
          name: 'value',
        });
        const stepInput = createInput(
          'Шаг для значения',
          valueInputType === 'float' ? '0.1' : '1',
          styleNames_1.default.formStepInput,
        );
        form.insertBefore(stepInput.parentElement, valueInput.parentElement);
        break;
      }
      case 'text': {
        newValueInput = (0, utils_1.createElement)('input', {
          type: 'text',
          className: styleNames_1.default.formValueInput,
          required: true,
          name: 'value',
        });
        break;
      }
      case 'checkbox': {
        newValueInput = (0, utils_1.createElement)('input', {
          type: 'checkbox',
          className: styleNames_1.default.formValueInput,
          name: 'value',
        });
        break;
      }
    }
    valueInput.replaceWith(newValueInput);
    valueInput = newValueInput;
    window.setTimeout(() => valueInput.focus());
  };
  if (oldValues) {
    switch (typeof oldValues.value) {
      case 'object': {
        if (Array.isArray(oldValues.value)) {
          valueInputType = 'select';
          const newValueInput = (0, utils_1.createElement)('select');
          const select = createOptionsForm(oldValues.value);
          valueInput.replaceWith(select);
          valueInput = newValueInput;
        } else {
          valueInputType = 'details';
          valueInput.disabled = true;
          valueInput.value = 'объект';
          valueInput.type = 'text';
        }
        break;
      }
      case 'boolean':
      case 'number':
      case 'string': {
        const input = targetNode.querySelector('input');
        valueInput.type = input.type;
        valueInput.value = `${oldValues.value}`;
        valueInputType = input.type;
        if (input.type === 'number') {
          valueInputType = oldValues.type;
          valueInput.step = input.step;
          const stepInput = createInput(
            'Шаг для значения',
            input.step,
            styleNames_1.default.formStepInput,
          );
          form.insertBefore(stepInput.parentElement, valueInput.parentElement);
        } else if (input.type === 'checkbox') {
          valueInput.checked = !!oldValues.value;
        }
        break;
      }
    }
    const selectedOption = valueInputTypeSelect.options.namedItem(
      `c_opt_${valueInputType}`,
    );
    if (selectedOption) {
      options[0].selected = false;
      selectedOption.selected = true;
    }
  }
  (0, utils_1.createElement)(
    'button',
    {
      className: styleNames_1.default.formSubmitButton,
      textContent: 'Сохранить',
      type: 'button',
      onclick: handleSaveButtonClick,
    },
    form,
  );
  (0, utils_1.createElement)(
    'p',
    {
      className: styleNames_1.default.formValidationError,
    },
    form,
  );
  return form;
};
const handleSaveButtonClick = () => {
  var _a;
  const form = document.querySelector(`.${styleNames_1.default.form}`);
  if (!form) {
    (0, utils_1.emit)(
      'error',
      'форма создания нового поля не найдена. Закройте и откройте окно конфига и попробуйте снова',
    );
    return;
  }
  const keyInput = form.querySelector(`.${styleNames_1.default.formKeyInput}`);
  const nameInput = form.querySelector(`.${styleNames_1.default.formNameInput}`);
  const valueInput = form.querySelector(`.${styleNames_1.default.formValueInput}`);
  const valueInputTypeSelect = form.querySelector(
    `.${styleNames_1.default.formValueTypeInput}`,
  );
  if (!form.checkValidity()) {
    form.reportValidity();
    return;
  }
  const key = keyInput.value,
    name = nameInput.value,
    target = oldValues && form.parentElement ? form.parentElement : targetNode;
  const isKeyUsed = Array.from(target.children).find((node) => {
    return node.nodeName !== 'SUMMARY' && node.querySelector(`[data-key=${key}]`);
  });
  if (isKeyUsed) {
    setError('в этом разделе уже есть поле с таким ключём');
    return;
  }
  let value,
    step = null;
  const valueInputType = valueInputTypeSelect.value;
  switch (valueInputType) {
    case 'select': {
      value = Array.from(
        form.getElementsByClassName(styleNames_1.default.optionsFormOptionInputs),
      ).map((div) => {
        return {
          value: div.querySelector(`.${styleNames_1.default.formValueInput}`).value,
          name: div.querySelector(`.${styleNames_1.default.formNameInput}`).value,
          chosen: div.querySelector('[type=radio]').checked,
        };
      });
      let isValuesUnique = true;
      for (let i = 0; i < value.length && isValuesUnique; i++) {
        for (let j = i + 1; j < value.length && isValuesUnique; j++) {
          if (value[i].value === value[j].value || value[i].name === value[j].name) {
            isValuesUnique = false;
            setError('Значения и названия опций должны быть уникальными');
            return;
          }
        }
      }
      break;
    }
    case 'text': {
      value = valueInput.value;
      value = value.replace(/[ ]+/g, '_');
      break;
    }
    case 'float':
    case 'integer': {
      value = Number(valueInput.value.replace(',', '.'));
      step = valueInput.step;
      break;
    }
    case 'checkbox': {
      value = valueInput.checked;
      break;
    }
    case 'details': {
      value = oldValues ? oldValues.value : {};
      break;
    }
  }
  document.querySelector(`.${styleNames_1.default.wrapper}`).dataset.isChanged = 'true';
  (0, createConfigPage_1.createConfigPageRecursion)(
    { [key]: { name, value, type: valueInputType, step } },
    target,
  );
  form.remove();
  let saveInDefault = '';
  if (!oldValues) {
    saveInDefault = 'key name value';
    if (valueInputType === 'details') {
      const newTarget = Array.from(target.children).find((node) =>
        node.querySelector(`[data-key=${key}]`),
      );
      if (!newSection) {
        newSection = newTarget;
      }
      newTarget === null || newTarget === void 0
        ? void 0
        : newTarget.appendChild(createForm({ targetNode: newTarget }));
    }
  } else {
    saveInDefault =
      ((_a = targetNode.querySelector(`[data-key=${oldValues.key}]`)) === null ||
      _a === void 0
        ? void 0
        : _a.dataset.saveInDefault) || '';
    saveInDefault +=
      key !== oldValues.key && !saveInDefault.includes('key') ? ' key' : '';
    saveInDefault +=
      name !== oldValues.name && !saveInDefault.includes('name') ? ' name' : '';
    if (
      (JSON.stringify(value) != JSON.stringify(oldValues.value) &&
        !saveInDefault.includes('value')) ||
      oldValues.type !== valueInputType
    ) {
      saveInDefault += ' value';
    }
    saveInDefault = saveInDefault.trimStart();
  }
  target.querySelector(`[data-key=${key}]`).dataset.saveInDefault = saveInDefault;
  document.removeEventListener('click', removeForm);
};
const createInput = (descriptionText, value, style, parent) => {
  const wrapper = (0, utils_1.createElement)(
    'div',
    null,
    parent,
    (0, utils_1.createElement)('span', { innerHTML: `${descriptionText}:` }),
  );
  return (0, utils_1.createElement)(
    'input',
    { type: 'text', required: true, className: style, value: value },
    wrapper,
  );
};
const removeForm = (e) => {
  const form = document.querySelector(`.${styleNames_1.default.form}`);
  if (form && !e.composedPath().includes(form)) {
    if (oldValues) {
      form.replaceWith(targetNode);
    } else {
      if (isCreatedSection) {
        newSection === null || newSection === void 0 ? void 0 : newSection.remove();
        newSection = null;
        isCreatedSection = false;
      }
      form.remove();
    }
    document.removeEventListener('click', removeForm);
  }
};
const setError = (text) => {
  const form = document.querySelector(`.${styleNames_1.default.form}`);
  const errorMessage =
    form === null || form === void 0
      ? void 0
      : form.querySelector(`.${styleNames_1.default.formValidationError}`);
  errorMessage.style.display = 'block';
  errorMessage.innerHTML = text;
  const removeError = () => {
    errorMessage.removeAttribute('style');
    form === null || form === void 0
      ? void 0
      : form.removeEventListener('click', removeError);
  };
  () =>
    form === null || form === void 0
      ? void 0
      : form.addEventListener('click', removeError);
};
const createOptionsForm = (oldValues) => {
  const form = (0, utils_1.createElement)('div', {
    className: styleNames_1.default.optionsForm,
  });
  (0, utils_1.createElement)(
    'h3',
    {
      innerHTML: 'Создайте опции',
    },
    form,
  );
  const optionInputs = [];
  (0, utils_1.createElement)(
    'div',
    {
      className: styleNames_1.default.optionsFormTableHead,
    },
    form,
    [
      (0, utils_1.createElement)('p', { innerHTML: 'Имя' }),
      (0, utils_1.createElement)('p', { innerHTML: 'Значение' }),
    ],
  );
  const createOptionInputs = (option) => {
    const optionNameInput = (0, utils_1.createElement)(
      'input',
      {
        type: 'text',
        className: styleNames_1.default.formNameInput,
        required: true,
        value: (option === null || option === void 0 ? void 0 : option.textContent) || '',
        name: 'optionName',
      },
      form,
    );
    const optionValueInput = (0, utils_1.createElement)(
      'input',
      {
        type: 'text',
        className: styleNames_1.default.formValueInput,
        required: true,
        value: (option === null || option === void 0 ? void 0 : option.value) || '',
        name: 'optionValue',
      },
      form,
    );
    const optionSelectedInput = (0, utils_1.createElement)('input', {
      type: 'radio',
      checked: option === null || option === void 0 ? void 0 : option.selected,
      name: 'chosen',
      value: optionInputs.length.toString(),
    });
    const optionInputsContainer = (0, utils_1.createElement)(
      'div',
      { className: styleNames_1.default.optionsFormOptionInputs },
      null,
      [optionNameInput, optionValueInput, optionSelectedInput],
    );
    (0, helpers_1.createControlConfigButton)('delete', optionInputsContainer, () => {
      optionInputsContainer.remove();
      if (
        form.querySelectorAll(`.${styleNames_1.default.optionsFormOptionInputs}`)
          .length === 0
      ) {
        createOptionInputs();
      }
    });
    form.insertBefore(optionInputsContainer, addNewOptionButton);
    window.setTimeout(() => optionNameInput.focus());
  };
  const addNewOptionButton = (0, utils_1.createElement)(
    'button',
    {
      textContent: 'Добавить опцию',
      className: styleNames_1.default.optionsFormAddOptionButton,
      type: 'button',
      onclick: () => createOptionInputs(),
    },
    form,
  );
  if (oldValues.length > 0) {
    oldValues.forEach((option) => createOptionInputs(option));
  } else {
    createOptionInputs(
      (0, utils_1.createElement)('option', {
        value: 'none',
        innerHTML: 'не выбрано',
        selected: true,
      }),
    );
    createOptionInputs();
  }
  return form;
};
exports.default = createForm;
//# sourceMappingURL=createForm.js.map
