import { normalizeViewportOrientation } from './orientation.js';

export function createSettingsController({
  modal,
  openButton,
  okButton,
  cancelButton,
  closeButton,
  documentTarget = document,
  capture,
  restore,
  getOrientation,
  setOrientationInput,
  readOrientationInput,
  onOpen = () => {},
  onSave,
}) {
  let snapshot = null;

  function open() {
    snapshot = capture();
    setOrientationInput(getOrientation());
    onOpen(snapshot);
    modal.classList.add('show');
  }

  function close(save) {
    if (save) {
      onSave(normalizeViewportOrientation(readOrientationInput()), snapshot);
    } else if (snapshot) {
      restore(snapshot);
      setOrientationInput(snapshot.viewportOrientation);
    }
    modal.classList.remove('show');
  }

  const save = () => close(true);
  const cancel = () => close(false);
  const overlayClick = event => {
    if (event.target === modal) cancel();
  };
  const escape = event => {
    if (event.code === 'Escape' && modal.classList.contains('show')) cancel();
  };

  openButton.addEventListener('click', open);
  okButton.addEventListener('click', save);
  cancelButton.addEventListener('click', cancel);
  closeButton.addEventListener('click', cancel);
  modal.addEventListener('click', overlayClick);
  documentTarget.addEventListener('keydown', escape);

  return {
    open,
    close,
    destroy() {
      openButton.removeEventListener('click', open);
      okButton.removeEventListener('click', save);
      cancelButton.removeEventListener('click', cancel);
      closeButton.removeEventListener('click', cancel);
      modal.removeEventListener('click', overlayClick);
      documentTarget.removeEventListener('keydown', escape);
    },
  };
}
