module Transit
  class RouteStop < Record
    with_options :readonly => true do |r|
      r.belongs_to :route
      r.belongs_to :direction
      r.belongs_to :stop
    end

    include Locatable

    def self.nearby(location, limit = 5)
      return [] if location.nil?
      stops = eager_load(:stop, :direction).find_nearby(location)
      stops.uniq_by(&:stop_name)[0, limit]
    end

    def route_name
      route.name
    end

    def stop_name
      stop.name
    end

    def latitude
      stop.latitude
    end

    def longitude
      stop.longitude
    end

    def geohash
      stop.geohash
    end

    def location
      stop.location
    end

    def other_direction
      @other_direction ||= route.directions.reject { |d| d == direction }.first
    end

    def alternate_stop
      @alternate_stop ||= other_direction &&
        other_direction.stops.find_by_name(stop.name)
    end

    def alternate
      @alternate ||= other_direction &&
        alternate_stop &&
        other_direction.route_stops.find_by_stop_id(alternate_stop.id)
    end

    def has_other_stops
      if stop.route_stops.count > 1
        stop
      end
    end

    def predictions
      @predictions ||= Prediction.find_all_by_route_stop(self)
    end

    def predictions_path
      "/routes/#{route_id}/directions/#{direction.to_param}/stops/#{id}"
    end

    def as_json(options = {})
      {
        :id        => self.id,
        :routeId   => self.route_id,
        :stopId    => self.stop_id,
        :routeName => self.route_name,
        :stopName  => self.stop_name,
        :direction => self.direction,
        :alternate => self.alternate && {
          :id        => self.alternate.id,
          :routeId   => self.alternate.route_id,
          :direction => self.alternate.direction
        },
        :latitude  => self.latitude,
        :longitude => self.longitude,
        :geohash   => self.geohash
      }
    end
  end
end
