# encoding: UTF-8

#影院信息Mongo数据模型
#该数据模型包括适合用于地理运行的信息
=begin rdoc
    id: 影院id,
    name: 影院名称,
    address: 影院地址,
    description: 影院描述,
    phone: 联系电话,
    lon: 经度,
    lat: 维度,
    coordinates: 经纬度坐标 point(116.518314,39.923626),
    cinema_chain_id: 院线id ??,
    nearby: 周边,
    traffic: 乘车路线,
    images: 图片,
    city: {
      id: 城市id,
      name: 城市名
    },
    area: {
      id: 城区id,
      name: 城区名,
    }
=end

require 'mongoid'
require 'mongoid_geospatial'


class MongoCinema
  include Mongoid::Document
  include Mongoid::Geospatial

  field :cinema_id,type: Integer
  field :name,type: String
  field :address,type: String
  field :description,type: String
  field :phone,type: String
  field :lon,type: String
  field :lat,type: String
  field :coordinates,type: Point,:spatial => true
  field :cinema_chain_id,type: String
  field :nearby,type: String
  field :traffic,type: String
  field :images,type: String
  field :city,type: Hash
  field :area,type: Hash

  index({ cinema_id: 1 }, { unique: true, background: true })
  index({ "city.id" => 1 }, { background: true })
  index({ "area.id" => 1 }, { background: true })
  index({ "cinema_chain_id" => 1 }, { background: true })

  # index([[:coordinates, Mongo::GEO2D]], background: true )
  # db.mongo_cinemas.ensureIndex({ "coordinates" : "2d" })

  def self.create_or_update_by_cinema_id(val)
    if (r = where(:cinema_id => val[:cinema_id])).exists?
      r.update(val)
    else
      create(val)
    end
  end

  #查找周边的影院
  #参数
  # :latitude  or lat
  # :longitude  or lon
  # :distance or max  (km)
  def self.near(p={:longitude => nil,:latitude  => nil,:distance => nil})
    #p={:longitude => 200,:lat  => 100,:distance => 20}
    lon = lat = distance = nil
    p.each_pair { |name, val|
      case name.to_sym
      when :longitude,:lon then lon = p.fetch(name)
      when :latitude,:lat then lat = p.fetch(name)
      when :distance,:max then distance = p.fetch(name)
      end
    }
    where(:coordinates => {"$near" => [lon,lat] , '$maxDistance' => distance.fdiv(93) } )
  end
end
