// @flow
import type { ThemeProps } from '../../../types';
import type { PatchworkTheme } from '../../../themes';
import type { SpaceKey, SpaceProps } from './spacing.proptypes';

const _getSpacingAmount = (
  theme: PatchworkTheme,
  regex: RegExp,
  key: SpaceKey | SpaceKey[],
) => {
  const keys = Array.isArray(key) ? key : [key];
  const heightKeys = keys.filter(k => regex.test(k));

  // First one wins in case of conflict.
  if (!heightKeys[0]) {
    return;
  }
  const regexResult = regex.exec(heightKeys[0]);
  if (regexResult === null) return '0';
  const [, level] = regexResult;
  if (level === '0' || level === 'auto') {
    return level;
  }
  return level != null ? theme.spacing[`s${level}`] : '0';
};

const _getSpacingTop = (
  theme: PatchworkTheme,
  key: SpaceKey | SpaceKey[],
  mOrP: 'm' | 'p',
) =>
  _getSpacingAmount(
    theme,
    mOrP === 'm' ? /^m[vt]?([0-9])$/ : /^p[vt]?([0-9])$/,
    key,
  );

const _getSpacingRight = (
  theme: PatchworkTheme,
  key: SpaceKey | SpaceKey[],
  mOrP: 'm' | 'p',
) =>
  _getSpacingAmount(
    theme,
    mOrP === 'm' ? /^m[hr]?([0-9]|auto)$/ : /^p[hr]?([0-9])$/,
    key,
  );

const _getSpacingBottom = (
  theme: PatchworkTheme,
  key: SpaceKey | SpaceKey[],
  mOrP: 'm' | 'p',
) =>
  _getSpacingAmount(
    theme,
    mOrP === 'm' ? /^m[vb]?([0-9]|auto)$/ : /^p[bv]?([0-9])$/,
    key,
  );

const _getSpacingLeft = (
  theme: PatchworkTheme,
  key: SpaceKey | SpaceKey[],
  mOrP: 'm' | 'p',
) =>
  _getSpacingAmount(
    theme,
    mOrP === 'm' ? /^m[hl]?([0-9])$/ : /^p[hl]?([0-9])$/,
    key,
  );

export const getSpacingRules = ({
  theme,
  spacing,
}: ThemeProps & SpaceProps) => {
  if (!spacing) {
    return {};
  }

  const result = {};

  const marginTop = _getSpacingTop(theme, spacing, 'm');
  if (marginTop) result.marginTop = marginTop;

  const marginRight = _getSpacingRight(theme, spacing, 'm');
  if (marginRight) result.marginRight = marginRight;

  const marginBottom = _getSpacingBottom(theme, spacing, 'm');
  if (marginBottom) result.marginBottom = marginBottom;

  const marginLeft = _getSpacingLeft(theme, spacing, 'm');
  if (marginLeft) result.marginLeft = marginLeft;

  const paddingTop = _getSpacingTop(theme, spacing, 'p');
  if (paddingTop) result.paddingTop = paddingTop;

  const paddingRight = _getSpacingRight(theme, spacing, 'p');
  if (paddingRight) result.paddingRight = paddingRight;

  const paddingBottom = _getSpacingBottom(theme, spacing, 'p');
  if (paddingBottom) result.paddingBottom = paddingBottom;

  const paddingLeft = _getSpacingLeft(theme, spacing, 'p');
  if (paddingLeft) result.paddingLeft = paddingLeft;

  return result;
};
