require 'csv'

class CsvImport < ActiveRecord::Base

  attr_accessible :csv
  
  # Associations
  belongs_to :user

  # Paperclip
  has_attached_file :csv

  validates_attachment_presence :csv

  validates_attachment_content_type :csv,
    :content_type => [
      'text/csv',
      'text/comma-separated-values',
      'text/csv',
      'application/csv',
      'application/excel',
      'application/vnd.ms-excel',
      'application/vnd.msexcel',
      'text/anytext',
      'text/plain'
    ]
    
    
  def validate(klass, config, options = {})
    
    row_number = 0
    csv_contents = CSV.read(csv.path, col_sep: ';', encoding: 'UTF-8')
    csv_contents.shift
    
    csv_contents.each do |row|
      
      row_number += 1
      object = klass.new
            
      config.each do |k, v|
        object[k] = row[v].squeeze(' ').strip unless row[v].nil?
      end
      
      options.each do |k, v|
        object[k] = v.squeeze(' ').strip unless v.nil?
      end
            
      unless object.valid?
        object.errors.full_messages.each do |error|
          errors.add(csv_file_name, "#{I18n.t('alerts.row_has_errors', :row => row_number)}: #{error}")
        end
      end
    end
    errors.empty?
  end
    
  def import(klass, config, options = {})
    
    if validate(klass, config, options)
      
      self.subject_class = klass.name
      self.save
      
      csv_contents = CSV.read(csv.path, col_sep: ';', encoding: 'UTF-8')
      csv_contents.shift      
      csv_contents.each do |row|

        object = klass.new
              
        config.each do |k, v|
          object[k] = row[v].squeeze(' ').strip unless row[v].nil?
        end
        
        options.each do |k, v|
          object[k] = v.squeeze(' ').strip unless v.nil?
        end
        
        object.save
      end
      return true
    end
    false    
  end
      

end
