@use 'sass:color';
@use 'sass:math';
@use 'sass:string';
@use 'sass:list';
@use 'sass:map';
@use './configuration' as *;

// scss原生并没有提供字符串的替换函数，需自己编写函数来实现这个功能
@function str-replace($string, $search, $replace) {
  $index: string.index($string, $search);

  @if $index {
    @return string.slice($string, 1, $index - 1) + $replace +
      str-replace(
        string.slice($string, $index + string.length($search)),
        $search,
        $replace
      );
  }

  @return $string;
}

// 把svg字符串编码成符合浏览器css规则的字符串
@function encode-svg($str) {
  @return str-replace($str, '#', '%23');
}

// 把一个数四舍五入到指定位数小数
@function tofixed($n, $digits: 0) {
  @return math.div(
    math.round($n * math.pow(10, $digits)),
    math.pow(10, $digits)
  );
}

@function bem-ns($str) {
  @return $sar-namespace + $sar-block-separator + $str;
}

@function bem($b, $e: null, $m: null) {
  $result: '.' + $sar-namespace + $sar-block-separator + $b;
  @if $e {
    $result: $result + $sar-element-separator + $e;
  }
  @if $m {
    $result: $result + $sar-modifier-separator + $m;
  }
  @return $result;
}

// 兼容旧版本
@function str-split($string, $separator) {
  // empty array/list
  $split-arr: ();
  // first index of separator in string
  $index: string.index($string, $separator);
  // loop through string
  @while $index != null {
    // get the substring from the first character to the separator
    $item: string.slice($string, 1, $index - 1);
    // push item to array
    $split-arr: list.append($split-arr, $item);
    // remove item and separator from string
    $string: string.slice($string, $index + 1);
    // find new index of separator
    $index: string.index($string, $separator);
  }
  // add the remaining string to list (the last item)
  $split-arr: list.append($split-arr, $string);

  @return $split-arr;
}

@function three-to-six($str) {
  $first: string.slice($str, 1, 1);
  $second: string.slice($str, 2, 2);
  $three: string.slice($str, 3, 3);

  @return $first + $first + $second + $second + $three + $three;
}

$map-hex-decimal: (
  '0': 0,
  '1': 1,
  '2': 2,
  '3': 3,
  '4': 4,
  '5': 5,
  '6': 6,
  '7': 7,
  '8': 8,
  '9': 9,
  'a': 10,
  'b': 11,
  'c': 12,
  'd': 13,
  'e': 14,
  'f': 15,
);

@function hex-to-decimal($hex) {
  $hex: string.to-lower-case($hex);
  @return map.get($map-hex-decimal, string.slice($hex, 1, 1)) * 16 +
    map.get($map-hex-decimal, string.slice($hex, 2, 2));
}

@function hex-to-rgb($hex) {
  $hex: str-replace(#{$hex}, '#', '');
  $hex: if(string.length($hex) == 3, three-to-six($hex), $hex);

  $first: string.slice($hex, 1, 2);
  $second: string.slice($hex, 3, 4);
  $three: string.slice($hex, 5, 6);

  @return '#{hex-to-decimal($first)},#{hex-to-decimal($second)},#{hex-to-decimal($three)}';
}
