// csstyle for sass
// Clean, Simple Styling for the Web
// http://www.csstyle.io
// Copyright (c) 2014 Dave Geddes
// https://twitter.com/geddski
// https://github.com/geddski

$csstyle-component-symbol: '' !default;
$csstyle-option-symbol: '\\--' !default;
$csstyle-part-symbol: '__' !default;
$csstyle-tweak-symbol: '\\+' !default;
$csstyle-location-symbol: '\\@' !default;
$csstyle-root-id: 'csstyle' !default;

// build selectors
@function _build_selector($prefix, $names){
    $selector: "";

    @for $i from 1 through length($names){
      $selector: $selector + $prefix + nth($names, $i);

      @if($i != length($names)){
        $selector: $selector + ",";
      }
    }

    @return $selector;
}

// components
@mixin component($names...){
  #{_build_selector("." + $csstyle-component-symbol, $names)}{
    @content;
  }
}

// options
// override components
@mixin option($names...){
  #{_build_selector("&." + $csstyle-option-symbol, $names)}{
    @content;
  }
}

// parts
// make up the structure of a component
// override components
@mixin part($names...){
    // check if nested in an option
    $optionIndex: str-index(#{&}, "." + $csstyle-option-symbol);
    @if str-index($csstyle-option-symbol, "\\") == 1 and $optionIndex == null {
      $optionIndex: str-index(#{&}, "." + str-slice($csstyle-option-symbol, 2));
    }
    $optionIndex: 0 !default;
    $optionIndex: $optionIndex - 1;

    // check if nested in another part
    $partIndex: str-index(#{&}, $csstyle-part-symbol);
    $partIndex: 0 !default;
    $partIndex: $partIndex - 1;

    $component: str-slice(#{&}, 0, $optionIndex);

    // part is nested in an option
    @if $optionIndex > 0 {
      // part is also nested in another part
      @if ($partIndex > 0){
        #{_build_selector("&" + $csstyle-part-symbol, $names)}{
          @content;
        }
      }
      @else{
        #{_build_selector("& " + $component + $csstyle-part-symbol, $names)}{
          @content;
        }
      }
    }
    @else {
      #{_build_selector("&" + $csstyle-part-symbol, $names)}{
        @content;
      }
    }
}

// tweaks
// override components, options, and modifiers
@mixin tweak($names...){
  #{_build_selector("#" + $csstyle-root-id + " ." + $csstyle-tweak-symbol, $names)}{
    @content;
  }
}

// locations
// override components, parts, options, and tweaks
@mixin location($names...){
  @warn "locations will be deprecated soon. Please use components instead.";
  
  #{_build_selector("#" + $csstyle-root-id + " ." + $csstyle-location-symbol, $names)}{
    @content;
  }
}
