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

    csv_text = File.read("#{Rails.root.to_s}/doc/organizaciones.csv")
    csv = CSV.parse(csv_text, :headers => true)
    csv.each do |row|
      o = Organization.where(
        code: row[0].try(:strip),
        name: row[1].try(:strip),
        acronym: row[2].try(:strip)
      ).first_or_create(
        nature: row[3].try(:strip),
        status_legalization: row[4].try(:strip),
        starting_date: row[5].try(:strip),
        legalization_date: row[6].try(:strip),
        legal_representative: row[7].try(:strip),
        project_manager: row[8].try(:strip),
        project_manager_charge: row[9].try(:strip),
        objectives: row[10].try(:strip),
        address: row[11].try(:strip),
        department: row[12].try(:strip),
        city: row[13].try(:strip)
      )

      b = o.organization_branches.where(
        department: row[14].try(:strip),
        city: row[15].try(:strip),
        phone: row[16].try(:strip),
        fax: row[17].try(:strip),
        email: row[18].try(:strip),
        website: row[19].try(:strip),
        facebook: row[20].try(:strip),
        twitter: row[21].try(:strip),
        network: row[23].try(:strip)
      ).first_or_create

      b.organization_branch_areas.where(
        institutions: row[24].try(:strip),
        funding_source: row[25].try(:strip),
        main_activities: row[26].try(:strip),
        themes: row[27].try(:strip),
        population: row[28].try(:strip),
        department: row[29].try(:strip),
        city: row[30].try(:strip)
      ).first_or_create
    end
  end
end
