require 'csv'
class Exportation < ActiveRecord::Base

  attr_accessible :filename, :email, :downloaded, :deleted, :klass_name
  
  # Non database attributes
  attr_accessor :institution_id
  
  # Validations
  validates :email, presence: true, format: { with: /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i }
  
  # King Tokens
  can_has_tokens :download_exported_file, { days_valid: 3 }

  def conditions
    if institution_id.nil?
      '1 = 1'
    elsif klass_name.constantize.respond_to?(:active)
      { institution_id: institution_id, active: true }
    else
      { institution_id: institution_id }
    end
  end

  def file_path
    Rails.root.join('public', 'exports', filename)
  end

  def generate_csv_file
    CSV.generate do |csv|
      csv << header_csv
      klass_name.constantize.where(conditions).order(1).each do |item|
        csv << item.data_for_csv
      end
    end
  end

  def export_csv
    create_csv_file
    notify_to_user
  end

  def create_csv_file
    CSV.open(file_path, 'w') do |writer|
      writer << header_csv
      klass_name.constantize.order(1).each do |item|
        writer << item.data_for_csv
      end
    end
  end
  
  def header_csv
    translated_header = []
    klass_name.constantize.header_for_csv.each do |field|
      translated_header << I18n.translate("activerecord.attributes.#{klass_name.underscore}.#{field}")
    end
    translated_header
  end

  def notify_to_user
    self.set_download_exported_file_token
    UserMailer.dowload_exported_file(self).deliver    
  end
end
