//
// Copyright 2019 Stijn de Witt. Some rights reserved.
// Licensed under the MIT Open Source license. 
// https://opensource.org/licenses/MIT
// See LICENSE for details.
//
// Based on code copyright 2018 Google Inc. All Rights Reserved.
// Licensed under the Apache License, Version 2.0.
// http://www.apache.org/licenses/LICENSE-2.0
// See LICENSE-MDC for details.
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under these licenses is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the licenses for the specific language governing permissions and
// limitations under these licenses.
// 

@import "./constants";

// Calculate the luminance for a color.
// See https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests
@function luminance($color) {
  $red: nth($linear-channel-values, red($color) + 1);
  $green: nth($linear-channel-values, green($color) + 1);
  $blue: nth($linear-channel-values, blue($color) + 1);

  @return .2126 * $red + .7152 * $green + .0722 * $blue;
}

// Calculate the contrast ratio between two colors.
// See https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests
@function contrast($back, $front) {
  $backLum: luminance($back) + .05;
  $foreLum: luminance($front) + .05;

  @return max($backLum, $foreLum) / min($backLum, $foreLum);
}

// Determine whether the color is "light" or "dark".
@function tone($color) {
  @if $color == "dark" or $color == "light" {
    @return $color;
  }

  $minimumContrast: 3.1;

  $lightContrast: contrast($color, white);
  $darkContrast: contrast($color, rgba(black, .87));

  @if ($lightContrast < $minimumContrast) and ($darkContrast > $lightContrast) {
    @return "light";
  } @else {
    @return "dark";
  }
}

// Determine whether to use dark or light text on top of given color to meet accessibility standards for contrast.
// Returns "dark" if the given color is light and "light" if the given color is dark.
@function contrast-tone($color) {
  @return if(tone($color) == "dark", "light", "dark");
}
