class Panel::Gprs::BackEnd::LocationsController < OrbitBackendController

  #before_filter :clean_values, :only => [:create, :update]

  before_filter :force_order_for_visitor,:only => [:index, :new, :edit, :delete]
  before_filter :force_order_for_user,:except => [:get_locations,:index]
  #before_filter :for_app_sub_manager,:except => [:index, :new, :edit, :delete, :get_locations]

  def index
    @locations = Location.all
    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @locations }
    end
  end

  def new
    @location = Location.new

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @location }
    end
  end

  def edit
    @location = Location.find(params[:id])
  end

  def show
    @location = Location.find(params[:id])
    respond_to do |format|
      format.html
      format.json { render json: @location }
    end
  end

  def create
    @location = Location.new(params[:location])
    @location.save!
    redirect_to panel_gprs_back_end_locations_url
  end

  def update
    @location = Location.find(params[:id])
    @location.update_attributes(params[:location])
    redirect_to panel_gprs_back_end_locations_url
  end

  def destroy
    @location = Location.find(params[:id])
    @location.destroy
    redirect_to panel_gprs_back_end_locations_url

  end

  def get_locations
    locations = Location.all
    @data = Array.new

    locations.each do |location|
      picurl = location.file.blank? ? '' : "http://#{request.host_with_port + location.file.url}"
      thumburl = location.file.blank? ? '' : "http://#{request.host_with_port + location.file.thumb.url}"
      @data << { name: location.name,
                 pic_url: picurl,
                 thumb_url: thumburl,
                 longitude: location.longitude,
                 latitude: location.latitude,
                 description: location.description }
    end

    #print readable json
    render :json => JSON.pretty_generate({location: @data})

    #render :json => {location: @data}.to_json
  end
end
