
// Maps helpers
// ===================================

@function map-gets($map, $keys...) {
	@each $key in $keys {
		$map: map-get($map, $key);
	}

	@return $map;
}

@function map-extend($map, $maps.../*, $deep */) {
	$last: nth($maps, -1);
	$deep: $last == true;
	$max: if($deep, length($maps) - 1, length($maps));

	// Loop through all maps in $maps...
	@for $i from 1 through $max {
		// Store current map
		$current: nth($maps, $i);

		// If not in deep mode, simply merge current map with map
		@if not $deep {
			$map: map-merge($map, $current);
		} @else {
			// If in deep mode, loop through all tuples in current map
			@each $key, $value in $current {

				// If value is a nested map and same key from map is a nested map as well
				@if type-of($value) == "map" and type-of(map-get($map, $key)) == "map" {
					// Recursive extend
					$value: map-extend(map-get($map, $key), $value, true);
				}

				// Merge current tuple with map
				$map: map-merge($map, ($key: $value));
			}
		}
	}
	@return $map;
}

@function map-get-next($map, $key, $fallback: false) {

	// Check if map is valid
	@if type_of($map) == map {

		// Check if key exists in map
		@if map_has_key($map, $key) {

			// Init index counter variable
			$i: 0;

			// Init key index
			$key-index: false;

			// Traverse map for key
			@each $map-key, $map-value in $map {
				// Update index
				$i: $i + 1;

				// If map key found, set key index
				@if $map-key == $key {
					$key-index: $i;
				}

				// If next index return next value
				@if $i == $key-index + 1 {
					@return $map-value;
				}

				// If last entry return false
				@if $i == length($map) {
					@return $fallback;
				}
			}

			@warn 'No next map item for key #{$key}';
			@return $fallback;
		}

		@warn 'No valid key #{$key} in map';
		@return $fallback;
	}

	@warn 'No valid map';
	@return $fallback;
}
