// Mixins :: Reparent

// Dependencies
@import "../functions/get-selector";
@import "../functions/list-remove";
@import "../functions/str-explode";

@mixin reparent($class: false) {
  // Reparenting requires class to be passed in.
  // Use default Sass & if $class is not defined
  @if not $class or type-of($class) != "string" {
    & {
      @content;
    }
  }
  @else {
    // Convert the & selectors list into a usable string
    $selectors: inspect(&);
    $selector-list: ($selectors);

    @if str-index($selectors, " ") {
      // Split the string into a list of individual selectors
      $selector-list: _str-explode($selectors, " ");
    }

    $len: length($selector-list);

    // Get the current selector
    $selector: nth($selector-list, $len);

    // Reparent if the total list of $selectors is more than 3
    // This assumes:
    // grandparent(s) > parent > current
    @if $len >= 3 {
      // Get the parent selector
      $parent: nth($selector-list, $len - 1);
      // Retrieve the grandparents as a single selector
      $grandparents: _list-remove($selector-list, $parent);
      $grandparents: _list-remove($grandparents, $selector);
      // Transforms the list/string into a valid selector string
      $grandparents: _get-selector($grandparents);

      @if $grandparents {
        // Output:
        // grandparent(s) | reparent-selector | current
        @at-root #{$grandparents} #{$class} #{$selector} {
          @content;
        }
      }
      @else {
        // Transforms the list/string into a valid selector string
        $selector: _get-selector($selector);
        // Output:
        // reparent-selector | current
        @at-root #{$class} #{$selector} {
          @content;
        }
      }
    }
    // Has less than 3 total selector
    @else {
      // Transforms the list/string into a valid selector string
      $selector: _get-selector($selector);
      @at-root #{$class} #{$selector} {
        @content;
      }
    }
  }
}
