class Contact < ApplicationRecord
  require 'csv'

  # Associations
  belongs_to :city

  attr_accessor :state_id
  validates :name,     presence: true
  validates :phone,    presence: true
  validates :state_id, presence: true
  validates :city_id,  presence: true
  validates :kind,     presence: true
  validates :email,    presence: true
  validates :email, format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, on: :create }

  def self.to_csv
    attributes = %w{name phone email state_name city_name kind sdate}

    CSV.generate(headers: true) do |csv|
      csv << %w{Nombre Telefono Correo Departmento Ciudad Tipo Fecha}

      all.each do |c|
        csv << attributes.map{ |attr| c.send(attr) }
      end
    end
  end

  def state_name
    city.nil? ? "¿?" : "#{city.state.name}"
  end

  def city_name
    city.nil? ? "¿?" : "#{city.name}"
  end

  def origin
    city.nil? ? "¿?" : "#{city.full_name}"
  end

  def sdate
    created_at.nil? ? "¿?" : "#{I18n.l created_at, format: :long}"
  end

end
