//
// Copyright IBM Corp. 2016, 2018
//
// This source code is licensed under the Apache-2.0 license found in the
// LICENSE file in the root directory of this source tree.
//

//-------------------------
// 🎌 Feature Flags
//-------------------------

/// Initialize the feature flag map with default values.
/// @access public
/// @type Map
/// @group feature-flags
/// @example
/// @example scss - Overriding defaults from the `$default-feature-flags` map
///   $feature-flags: (
///     ui-shell: false,
///     grid: true,
///     grid-columns-16: false,
///     grid--fallback: false,
///   );
$feature-flags: () !default;

/// Default feature flag values
/// @access private
/// @type Map
/// @group feature-flags
$default-feature-flags: (
  ui-shell: true,
  grid: true,
  grid-columns-16: false,
  grid--fallback: false,
  enable-css-custom-properties: false,
);

/// @access private
/// @type Bool
/// @group feature-flags
$did-warn-diverged-feature-flags: false !default;

/// Look for user-defined feature flags that are different from default ones, and warn them before merging them.
/// @access private
/// @param {Map} $dst - The feature flags to merge to (default feature flags)
/// @param {Map} $src - The feature flags to merge from (user-defined feature flags)
/// @returns {Map} - The result of `map-merge($dst, $src)`
/// @example scss
///   $feature-flags: merge-feature-flags($default-feature-flags, $feature-flags);
/// @group feature-flags
@function merge-feature-flags($dst, $src) {
  @if (not $did-warn-diverged-feature-flags) {
    $diverged: ();

    @each $name, $value in $src {
      @if (
        map-has-key($dst, $name) == true and map-get($dst, $name) != $value
      ) {
        $diverged: append($diverged, $name);
      }
    }

    @if (length($diverged) > 0) {
      @warn 'Usage of non-default feature flags was found: #{$diverged}. ' +
        'Feature/code under non-default feature flags are either experimental, deprecated, or support for edge cases. ' +
        'They are subject to change any time. Use them at your own risk.';
      $did-warn-diverged-feature-flags: true !global;
    }
  }

  @return map-merge($dst, $src);
}

$feature-flags: merge-feature-flags($default-feature-flags, $feature-flags);

@if map-get($feature-flags, grid) != true {
  // We supported a flag for experimental grid in the past that we want to keep
  // supporting till our next major release. These two @if statements will assign
  // these values over into the map if they are defined.
  @if variable-exists(css--use-experimental-grid) == true {
    $feature-flags: map-merge(
      $feature-flags,
      (
        grid: $css--use-experimental-grid,
      )
    );
  }

  @if variable-exists(css--use-experimental-grid-fallback) == true {
    $feature-flags: map-merge(
      $feature-flags,
      (
        grid--fallback: $css--use-experimental-grid-fallback,
      )
    );
  }
}
