# == Schema Information
#
# Table name: nizza_properties
#
#  id               :integer          not null, primary key
#  property_type_id :integer
#  code             :string
#  name             :string
#  position         :integer
#  created_at       :datetime         not null
#  updated_at       :datetime         not null
#  properable_id    :integer
#  properable_type  :string
#

module Nizza
  class Property < ActiveRecord::Base

    # --- зависимости
    require_dependency '/nizza/property/hotels'
    require_dependency '/nizza/property/numbers'

    belongs_to :property_type
    belongs_to :properable, polymorphic: true

    acts_as_list

    has_many :property_options, -> { order(position: :asc) }, dependent: :destroy

    validates :name, presence: true

    HOTEL_PROPERTY = "Nizza::Hotel"
    NUMBER_PROPERTY = "Nizza::Number"

    alias type property_type
    alias options property_options

    def self.create_combo(name, items, code = nil)
      prop = Property.create(name: name, property_type: PropertyType.list, code: code)
      items.each { |item| prop.options << PropertyOption.create(name: item) }
      yield prop if block_given?
      prop
    end

    def self.create_number(name, code = nil)
      prop = Property.create(name: name, property_type: PropertyType.number, code: code)
      yield prop if block_given?
      prop
    end

    def self.create_bool(name, code = nil)
      prop = Property.create(name: name, property_type: PropertyType.bool, code: code)
      yield prop if block_given?
      prop
    end


    def list?
      type.code == PropertyType::LIST_CODE
    end

    def number?
      type.code == PropertyType::NUMBER_CODE
    end

    def bool?
      type.code == PropertyType::BOOL_CODE
    end

  end
end
