class Api::ComplaintsController < ApplicationController
  skip_before_filter :authenticate_user!
 
  def rss
   @complaints = Complaint.all
   respond_to do |format|
      format.xml
    end
  end
  
  def get_complaints_geolocation
    complaints = []
    if !params[:lat].nil? && !params[:lng].nil? && !params[:lat].blank? && !params[:lng].blank?
      lat = params[:lat].to_i
      lng = params[:lng].to_i
      if lat != 0 && lng != 0
        addresses = Address.find_by_sql("SELECT * FROM
                                         (SELECT id, (6371 * acos(cos(radians(#{params[:lat]})) * cos(radians(lat)) *
                                                      cos(radians(lng) - radians(#{params[:lng]})) +
                                                      sin(radians(#{params[:lat]})) * sin(radians(lat))))
                                          AS distance
                                          FROM addresses) AS distances
                                          WHERE distance < 10
                                          ORDER BY distance")
                                           
        addresses.each do |address|
          complaint = Complaint.joins(:company => :address).where('addresses.id = ?', address.id).first
          complaints << complaint unless complaint.nil?
        end
        complaints = format_complaints(complaints) unless complaints.empty?
      end
    end
    render :json => { :complaints => complaints }
  end
  
protected

  def format_complaints(complaints)
    response = []
    complaints.each do |complaint|
      data = {}
      data[:id] = complaint.id
      data[:title] = complaint.title
      data[:avaliation] = complaint.avaliation.name
      data[:subject] = complaint.subject.name
      data[:feeling] = complaint.feeling.name
      data[:company] = complaint.company.name
      data[:description] = complaint.description
      data[:reply_message] = complaint.reply
      data[:avaliation_message] = complaint.avaliation_message
      data[:created_at] = l complaint.created_at, :format => :short_date
      response << data
    end
    return response
  end
end