class Shoulda::Matchers::Line

@private

def determine_where_to_break_line(line, args)

def determine_where_to_break_line(line, args)
  direction = args.fetch(:direction)
  index = TERMINAL_WIDTH
  offset = OFFSETS.fetch(direction)
  while line[index] !~ /\s/ && (0...line.length).cover?(index)
    index += offset
  end
  index
end

def initialize(line, indent: 0)

def initialize(line, indent: 0)
  @indent = indent
  @original_line = @line_to_wrap = Text.new(line)
  @indentation = ' ' * indent
  @indentation_read = false
end

def normalize_whitespace(string)

def normalize_whitespace(string)
  indentation + string.strip.squeeze(' ')
end

def read_indentation

def read_indentation
  initial_indentation = ' ' * indent
  match = line_to_wrap.match_as_list_item
  if match
    initial_indentation + (' ' * match[1].length)
  else
    initial_indentation
  end
end

def wrap

def wrap
  if line_to_wrap.indented?
    [line_to_wrap]
  else
    lines = []
    loop do
      @previous_line_to_wrap = line_to_wrap
      new_line = (indentation || '') + line_to_wrap
      result = wrap_line(new_line)
      lines << normalize_whitespace(result[:fitted_line])
      unless @indentation_read
        @indentation = read_indentation
        @indentation_read = true
      end
      @line_to_wrap = result[:leftover]
      if line_to_wrap.to_s.empty? || previous_line_to_wrap == line_to_wrap
        break
      end
    end
    lines
  end
end

def wrap_line(line, direction: :left)

def wrap_line(line, direction: :left)
  index = nil
  if line.length > TERMINAL_WIDTH
    index = determine_where_to_break_line(line, direction: :left)
    if index == -1
      index = determine_where_to_break_line(line, direction: :right)
    end
  end
  if index.nil? || index == -1
    fitted_line = line
    leftover = ''
  else
    fitted_line = line[0..index].rstrip
    leftover = line[index + 1 .. -1]
  end
  { fitted_line: fitted_line, leftover: leftover }
end