// @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]|auto)$/ : /^p[hl]?([0-9])$/,
    key,
  );

// For embedding in a template string.
export const getSpacingRules = ({
  theme,
  spacing,
}: {|
  ...ThemeProps,
  ...SpaceProps,
|}): string => {
  if (!spacing) {
    return '';
  }

  // Set spacing for all breakpoints.
  const marginTop = _getSpacingTop(theme, spacing, 'm');
  const marginRight = _getSpacingRight(theme, spacing, 'm');
  const marginBottom = _getSpacingBottom(theme, spacing, 'm');
  const marginLeft = _getSpacingLeft(theme, spacing, 'm');
  const paddingTop = _getSpacingTop(theme, spacing, 'p');
  const paddingRight = _getSpacingRight(theme, spacing, 'p');
  const paddingBottom = _getSpacingBottom(theme, spacing, 'p');
  const paddingLeft = _getSpacingLeft(theme, spacing, 'p');

  return [
    marginTop ? `margin-top: ${marginTop};\n` : '',
    marginRight ? `margin-right: ${marginRight};\n` : '',
    marginBottom ? `margin-bottom: ${marginBottom};\n` : '',
    marginLeft ? `margin-left: ${marginLeft};\n` : '',
    paddingTop ? `padding-top: ${paddingTop};\n` : '',
    paddingRight ? `padding-right: ${paddingRight};\n` : '',
    paddingBottom ? `padding-bottom: ${paddingBottom};\n` : '',
    paddingLeft ? `padding-left: ${paddingLeft};\n` : '',
  ].join('');
};
