class Api::DenouncementsController < ApiController
  respond_to :json
  skip_before_filter :verify_authenticity_token, only: [:vehicles, :request_notifications]

  def vehicles
    callback = params[:callback]

    @complaint = Denouncement.new()
    @complaint.place = params[:place].to_s rescue nil
    @complaint.plate = "N-"+params[:plate].to_s rescue nil
    @complaint.complaint_date = params[:complaint_date].to_s rescue nil
    @complaint.comment = params[:comment].to_s rescue nil
    @complaint.picture = params[:file] if params[:file].present?
    if @complaint.save
      UserMailer.delay.notify_new_denouncement(@complaint)
      content = { :response  => 'success', :denouncement_id => @complaint.id }.to_json
    else
      content = { :response  => 'failed' }.to_json
    end
    respond_to do |format|
      format.html {
        render json: "#{callback}(#{content})"
      }
      format.json { 
        render :json => "#{callback}(#{content})"
      }
      format.html
    end
  end

  def request_notifications
    callback = params[:callback]
    @complaint = DenouncementTracking.new()
    @complaint.denouncement_id = Denouncement.last.id
    @complaint.informer_name = params[:name].to_s rescue nil
    @complaint.informer_email = params[:email].to_s rescue nil
    if @complaint.save
      #UserMailer.delay.notify_new_denouncement(@complaint)
      content = { :response  => 'success', :denouncement_id => @complaint.id }.to_json
    else
      content = { :response  => 'failed' }.to_json
    end
    respond_to do |format|
      format.html {
        render json: "#{callback}(#{content})"
      }
      format.json { 
        render :json => "#{callback}(#{content})"
      }
      format.html
    end
  end

  def services
    callback = params[:callback]
    @complaint = Complaint.new(params[:complaint]) rescue nil 
    @complaint.textcaptcha
    @complaint.skip_textcaptcha = true
    if @complaint.save
      @complaint.confirmed = true
      @complaint.delay.deliver_complaint 
      content = { :response  => 'success' }.to_json
    else
      content = { :response  => 'failed' }.to_json
    end
    respond_to do |format|
      format.json { 
        render :json => "#{callback}(#{content})"
      }
    end
  end

end
