class Mapping < ActiveRecord::Base

  scope :topicmapping, -> { where(mappable_type: :Topic) }
  scope :synapsemapping, -> { where(mappable_type: :Synapse) }

  belongs_to :mappable, polymorphic: true
  belongs_to :map, :class_name => "Map", :foreign_key => "map_id", touch: true
  belongs_to :user

  validates :xloc, presence: true, 
    unless: Proc.new { |m| m.mappable_type == 'Synapse' }
  validates :yloc, presence: true,
    unless: Proc.new { |m| m.mappable_type == 'Synapse' }
  validates :map, presence: true
  validates :mappable, presence: true
  
  def user_name
    self.user.name
  end

  def user_image
    self.user.image.url
  end

  def as_json(options={})
    super(:methods =>[:user_name, :user_image])
  end

  def authorize_to_show(user)
    if ((self.map.permission == "private" && self.map.user != user) ||
         (self.mappable.permission == "private" && self.mappable.user != user))
      return false
    end
    return self
  end

end