require 'turnip/node/base'
require 'turnip/table'

module Turnip
  module Node
    #
    # @note Step metadata generated by Gherkin
    #
    #     {
    #       type: :Step,
    #       location: { line: 10, column: 3 },
    #       keyword: 'Step',
    #       text: 'Step description',
    #       argument: {}, # DocString or DataTable
    #     }
    #
    class Step < Base
      def keyword
        # TODO: Do we want to keep the whitespace?
        @raw.keyword + ' '
      end

      def text
        @raw.text
      end

      #
      # Backward compatibility
      #
      def description
        text
      end

      def argument
        @argument ||= case
                      when @raw.block&.is_a?(CukeModeler::DocString)
                        doc_string(@raw.block)
                      when @raw.block&.is_a?(CukeModeler::Table)
                        data_table(@raw.block)
                      end
      end

      def to_s
        "#{keyword}#{text}"
      end

      private

      def doc_string(doc)
        doc.content
      end

      def data_table(table)
        rows = table.rows.map do |row|
          row.cells.map do |cell|
            cell.value
          end
        end
        Turnip::Table.new(rows)
      end
    end
  end
end
