// @flow

import Color from 'color';
import type { ThemeOverrides } from './theme.types';
import { whitelabelDefaults } from './whitelabel-defaults.theme';
import type { ColorPalette } from '../mixins/branding';

type ColorTable = {
  [semanticName: string]: string,
};

/**
 * These are the magic values for darkening and lightening
 */
export const _whiteLabelShadingValues = {
  dark: 0.3,
  fg: 0.5,
  bg: 0.5,
};

/**
 * Generates colours with brand naming conventions for PatchworkTheme.colorPalette
 */
export const _generateBrandColors = (
  brandKeyword?: string,
  color?: ?string,
): ColorTable =>
  brandKeyword === undefined || color === undefined || color === null
    ? {}
    : {
        [`brand-${brandKeyword}-base`]: color,
        [`brand-${brandKeyword}-dark`]: Color(color)
          .darken(_whiteLabelShadingValues.dark)
          .hex(),
        [`brand-${brandKeyword}-fg`]: Color(color)
          .darken(_whiteLabelShadingValues.fg)
          .hex(),
        [`brand-${brandKeyword}-bg`]: Color(color)
          .lighten(_whiteLabelShadingValues.bg)
          .hex(),
      };

export const _generateAuxColors = (color?: string): ColorTable =>
  color === undefined
    ? {}
    : {
        'aux-1': Color(color)
          .lighten(_whiteLabelShadingValues.bg)
          .hex(),
        'aux-2': color,
        'aux-3': Color(color)
          .darken(_whiteLabelShadingValues.dark)
          .hex(),
        'aux-4': Color(color)
          .darken(_whiteLabelShadingValues.fg)
          .hex(),
      };

/**
 * When given a base colorPalette, generates shades of primary and secondary colour overrides
 * @param {PatchworkTheme.colorPalette} colorPalette
 * @param {String} primary
 * @param {String} secondary
 */
export const _getColorPaletteOverrides = (
  colorPalette: ColorPalette,
  primary?: string,
  secondary?: string,
) => ({
  ...colorPalette,
  ..._generateAuxColors(primary),
  ..._generateBrandColors('primary', primary),
  ..._generateBrandColors('secondary', secondary),
});

export const createWhitelabelTheme = ({
  primary,
  secondary,
  buttonBorderRadius,
}: ThemeOverrides) => {
  const newTheme = { ...whitelabelDefaults };

  const newColorPalette = _getColorPaletteOverrides(
    whitelabelDefaults.colorPalette,
    primary,
    secondary,
  );

  newTheme.colorPalette = newColorPalette;

  if (buttonBorderRadius != null) {
    newTheme.buttonBorderRadius = buttonBorderRadius;
  }
  return newTheme;
};
