namespace :agreements do
  desc 'Load agreements table'
  task :load => [:environment] do
    require 'csv'

    line     = 0
    csv_text = File.read("#{Rails.root}/doc/agreements.csv")
    csv      = CSV.parse(csv_text, headers: false)
    csv.each do |row|
      line += 1
      begin
        o = Document.where(
          name: row[0].try(:strip),
          institution_id: 9,
          information_standard_id: 42
        ).first_or_initialize(
          description: row[1].try(:strip),
          active: true,
          downloads: 0
        )

        if File.exists?("#{Rails.root}/doc/agreements/Acuerdo #{row[0].try(:strip)}.pdf")
          o.datafile = File.open("#{Rails.root}/doc/agreements/Acuerdo #{row[0].try(:strip)}.pdf")
          if o.save
            puts "Linea #{line}: #{row[0].try(:strip)} ... OK"
          else
            puts "Linea #{line}: #{row[0].try(:strip)} ... #{o.errors.full_messages.join(', ')}."
          end
        else
          puts "Linea #{line}: No existe el archivo #{row[0].try(:strip)}"
        end
      rescue
        puts "Linea #{line}: Error desconocido en la linea"
      end
    end
  end
end
