module DataHelpers
  class TrackLicensing
    class << self
      def get_data(data_type)
        case data_type
        when "txt"
          txt_data
        when "xls"
          xls_data
        else
          fail "unknown data type: #{data_type}!"
        end
      end

      private

      def txt_data
        ref = File.join template_dir, "valid_1.1.txt"
        str = File.read ref
        headers = str.split("\n")[0].split("\t")

        rows = str.split("\n").drop(1) # each row elem looks like "4918443\tNo\tNo\tNo\tNo\tUSA\tNo"
        # Because verification step currently hard codes a single release UPC we verify updates against:
        first_row = rows.assert_and_return_first_element.split("\t")

        res = {}
        headers.each_with_index do |header, index|
          res[header] = first_row[index]
        end
        res
      end

      def xls_data
        ref = File.join template_dir, "valid_1.1.xls"
        book = Spreadsheet.open ref
        sheet = book.worksheet 0
        content_row = sheet.row 1

        non_empty_rows = sheet_rows_containing_vals(sheet)

        # Because verification step currently hard codes a single release UPC we verify updates against:
        fail "Method only works for 1 row of content! Rows: #{non_empty_rows}" unless non_empty_rows == 2

        res = {}
        content_row.each_with_index do |cell, index|
          res[sheet.row(0)[index]] = cell
        end
        res
      end

      def sheet_rows_containing_vals(sheet) # looking at the first cell of each row
        rows = 0
        max_index = sheet.row_count - 1
        (0..max_index).each do |row_index|
          rows += 1 unless sheet.row(row_index)[0].to_s.empty?
        end
        rows
      end

      # TODO: move to a constant when data helpers aren't getting double-loaded
      def template_dir
        File.join(
          Support::Paths.assets,
          "templates",
          "oa_bulk_update_track_publishing"
        )
      end
    end
  end
end
