class Excel
  def self.execute(data, filename, output_location, batch_id)
    output_file ="#{output_location}/#{File.basename(filename, '.*')}_done.xlsx"

    workbook = prep_output_file(output_file)

    progressbar = ProgressBar.create(:title => "Writing Excel", :starting_at => 0, :total => data.count)

    data.each do | line |
      progressbar.increment
      add_line_to_report(workbook[0], line, batch_id, filename)
    end

    finish_output_file(workbook, output_file)
  end

  def self.add_line_to_report(sheet, line, batch_id, filename)
      sheet.insert_row(2)
      sheet.add_cell(2, 0, line[:account_id])
      sheet.add_cell(2, 1, line[:contract_id])
      sheet.add_cell(2, 2, line[:upc])
      sheet.add_cell(2, 3, line[:amount])
      sheet.add_cell(2, 4, line[:currency])
      sheet.add_cell(2, 5, line[:activity_year])
      sheet.add_cell(2, 6, line[:activity_month])
      sheet.add_cell(2, 7, line[:apply_year])
      sheet.add_cell(2, 8, line[:apply_month])
      sheet.add_cell(2, 9, line[:adjustment_type])
      sheet.add_cell(2, 10, line[:comment])
      sheet.add_cell(2, 11, line[:distribution_type])
      sheet.add_cell(2, 12, line[:reasons].any? ? 'N' : 'Y')
      sheet.add_cell(2, 13, line[:reasons].join(', '))
      sheet.add_cell(2, 14, filename)
      sheet.add_cell(2, 15, batch_id)
      sheet.add_cell(2, 16, line[:record_id])
  end

  def self.prep_output_file(output_file)
    FileUtils.cp('binary_templates/validation_template.xlsx', output_file)

    abort "Output file #{output_file} not found" unless File.exist?(output_file)

    RubyXL::Parser.parse(output_file)
  end

  def self.finish_output_file(workbook, output_file)
    workbook[0].delete_row(1)
    workbook.write(output_file)
  end

end


