/**
 * @license
 * Copyright Endlessjs. All Rights Reserved.
 * Licensed under the MIT License. See License.txt in the project root for license information.
 */

@function el-deep-find-value($theme, $key, $value) {
  $parent-value: map-get($theme, $value);

  @if ($parent-value != null) {
    @return el-deep-find-value($theme, $value, $parent-value);
  }

  @return $value;
}

@function el-process-theme($theme) {
  $processed-theme: ();
  @each $key, $value in $theme {
    $processed-theme: map-set($processed-theme, $key, el-deep-find-value($theme, $key, $value));
  }
  @return $processed-theme;
}

@function get-current-theme-name() {
  @if ($el-theme-name != null) {
    @return $el-theme-name;
  }

  @return get-last-enabled-theme();
}

@function el-theme($key) {

  $value: ();

  // in case of css custom properties - just returns var(--var-name) - the rest is a browser job
  @if ($el-enable-css-custom-properties == true) {
    // there is no way to check if variable exists as current execution context is outside of particular theme
    // because we process css in this mode only once! (and not for each theme)
    $value: var(--#{$key});
  } @else {
    // in a preprocess mode (el-install-global call) get ready value from $el-processed-theme variable
    @if ($el-theme-process-mode == 'pre-process') {
      $value: map-get($el-processed-theme, $key);
    }

    // otherwise lazily search for variable value
    @if ($el-theme-process-mode == 'lazy-process') {

      $el-theme-name: get-current-theme-name();

      $theme: el-get-registered-theme($el-theme-name);
      $value: el-deep-find-value($theme, $key, map-get($theme, $key));
    }
  }

  @if ($value == null) {
    @warn 'Endlessjs Theme: `el-theme()` cannot find value for key `' + $key + '` for theme `'+ $el-theme-name +'`';
  }

  @return $value;
}
