import { CSSProperties } from 'react';
import { fromNullable, map, getOrElse } from '../../fp/Option';
import { pipe, noop } from '../../fp/function';

const focusInput = (element: HTMLInputElement | null): void =>
  pipe(
    fromNullable(element),
    map(el => el.focus()),
    getOrElse(noop)
  );

const generateFocusBarStyle = (
  inputElement: HTMLInputElement | null
): CSSProperties => {
  const inputStyles = pipe(
    fromNullable(inputElement),
    map(input => getComputedStyle(input)),
    getOrElse(() => ({ width: '0px', paddingLeft: '0px' }))
  );
  const inputOffsetLeft = pipe(
    fromNullable(inputElement),
    map(input => input.offsetLeft),
    getOrElse(() => 0)
  );

  return {
    width: inputStyles.width,
    left: `calc(${inputOffsetLeft}px + ${inputStyles.paddingLeft})`,
  };
};

export { focusInput, generateFocusBarStyle };
