@import "theme.scss";
@import "functions";

$required-colors: "primary", "secondary", "shade", "error";
$required-default-hues: 400, 500, 600;
$required-shade-hues: 200, 300, 400, 500, 600, 700;

/**
 * Validates a palette map.
 */
@function _validate-palette-map ($palette-map) {

	// Check the required colors
	@each $required in $required-colors {
		@if (get_entry($palette-map, $required) == null) {
			@error "The palette map is missing a '#{$required}' color.";
		}
	}

	@each $name, $palette in $palette-map {

		// Ensure that a contrast is defined.
		@if (get_entry($palette, "contrast") == null) {
			@error "The palette '#{$name}' is missing a contrast color or map.";
		}

		// Ensure that the required hues are present
		$required-hues: if($name == "shade", $required-shade-hues, $required-default-hues);
		@each $required in $required-hues {
			@if (get_entry($palette-map, $required) == null) {
				@error "The palette '#{$name}' is missing a '#{$required}' hue.";
			}
		}
	}
}

/**
 * Determines whether a hue is the contrast map/color.
 */
@function _is-contrast ($hue) {
	@return type_of($hue) == "string" AND unquote($hue) == contrast
}

/**
 * Generates color variables for each hue in the palette.
 */
@mixin color-variables ($name, $palette) {
	@each $hue, $color in $palette {

		// Check if the hue is the contrast
		@if (_is-contrast($hue)) {

			// We now know that the color is either a map with contrast colors or a contrast color
			@if (type-of($color) != map) {

				// Add a contrast color for each hue which is NOT the contrast hue because the contrast is a color.
				@each $hue, $_ in $palette {
					@if (_is-contrast($hue) == false) {
						--#{$name}-#{$hue}-contrast: #{$color};
					}
				}

			} @else {

				// Add the contrast color for each hue defined in the contrast.
				@each $hue, $contrast-color in $color {
					--#{$name}-#{$hue}-contrast: #{$contrast-color};
				}
			}

		} @else {
			// Non contrast hue
			--#{$name}-#{$hue}: #{$color};
		}
	}
}

/**
 * Generates color variables for each color and it's hues and contrasts the palette map.
 */
@mixin theme-variables ($palette-map, $foreground: (230, 70%, 5%), $background: (0, 0%, 100%), $shadow: (230, 70%, 5%), $validate: true) {

	// Validate the map if necessary
	@if ($validate == true AND _validate-palette-map($palette-map) == false) {
		// We only go here if the palette was not validated..
		@warn "The palette '#{$palette-map}' is not valid.";
	}

	// Create color variables for each color
	@each $name, $palette in $palette-map {
		@include color-variables($name, $palette);
	}

	// Add the foreground, background and shadow
	--foreground: #{$foreground};
	--background: #{$background};
	--shadow: #{$shadow};
}

