class Particular < ApplicationRecord
  has_many :p_contacts, :as => :contactable, :dependent => :destroy
  accepts_nested_attributes_for :p_contacts, allow_destroy: true
  
  has_many :open_range_elements, :as => :element
  
  has_many :open_ranges, :through => :open_range_elements
  
  belongs_to :owner, :polymorphic => true
  validates :civilite, :presence => true, :if => :force_validate_name
  validates :name, :presence => true, :if => :force_validate_name
  validates :firstname, :presence => true, :if => :force_validate_name
  validates :email, :presence => true, :format => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, :if => :force_email_validation
  validates :address_2, :presence => true, :if => :force_validation
  validates :cp, :presence => true, :if => :force_validation
  validates :city, :presence => true, :if => :force_validation
  validates :country, :presence => true, :if => :force_validation
  validates :tel, :presence => true, :if => :force_validate_tel
  validates :organisation, :presence => true, :if => :force_organisation_validation
  attr_accessor :validate_email, :skip_email, :validate_name, :validate_tel, :skip_organisation
  
  belongs_to :particular_ref, :class_name => "Particular"
  def validate_pro
    true if self.force_validation and self.pro
  end
  
  def force_organisation_validation
    if self.force_validation and !self.skip_organisation
      true
    else
      false
    end
  end
  
  
  def force_email_validation
    if self.validate_email and (!self.skip_email or self.skip_email.to_s == "")
      true
    else
      false
    end
  end
  
  def force_validate_name
    if self.validate_name
      true
    else
      false
    end
  end
  
  def force_validate_tel
    if self.validate_tel and self.validate_tel.to_s != ""
      true
    else
      false
    end
  end
  
  def force_validation
  
    
    if self.skip_validation
      false
    else
      true
    end 
    
  end
  
  
  def long_name
    r = ""
    
    r+= "#{self.civilite} " if self.civilite 
    r+= "#{self.firstname} " if self.firstname 
    r+= "#{self.name} " if self.name 
    
    return r
    
      
  end
  def address_longue
    address_2.to_s + " " + address_3.to_s
  end

 
  
  def address_line
    r = ""
    r+= self.organisation+" " if self.organisation?
    r+= self.name+" " if self.name?
    r+= self.firstname+" " if self.firstname?
    r+= self.address_1+" " if self.address_1?
    r+= self.address_2+" " if self.address_2?
    r+= self.address_3+" " if self.address_3?
    r+= self.cp+" " if self.cp?
    r+= self.city+" " if self.city?
    return r
    
  end
  
end
