class NoUsesController < ApplicationController
  
  before_filter :require_login, :find_no_use, :only => [:create, :delete]  
  
  # GET /no_uses
  # GET /no_uses.json
  def index
    @no_uses = NoUse.all
    
    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @no_uses }
    end
  end

  # GET /no_uses/1
  # GET /no_uses/1.json
  def show
    @no_use = NoUse.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @no_use }
    end
  end

  # GET /no_uses/new
  # GET /no_uses/new.json
  def new
    @no_use = NoUse.new

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

  # GET /no_uses/1/edit
  def edit
    @no_use = NoUse.find(params[:id])
  end

  # POST /no_uses
  # POST /no_uses.json
  def create
    set_no_use(@no_use, User.current, true)

    # respond_to do |format|
      # if @no_use.save
        # format.html { redirect_to @no_use, notice: 'No use was successfully created.' }
        # format.json { render json: @no_use, status: :created, location: @no_use }
      # else
        # format.html { render action: "new" }
        # format.json { render json: @no_use.errors, status: :unprocessable_entity }
      # end
    # end
  end
  def delete
    set_no_use(@no_use, User.current, false)
  end

  # PUT /no_uses/1
  # PUT /no_uses/1.json
  def update
    @no_use = NoUse.find(params[:id])

    respond_to do |format|
      if @no_use.update_attributes(params[:no_use])
        format.html { redirect_to @no_use, notice: 'No use was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @no_use.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /no_uses/1
  # DELETE /no_uses/1.json
  def destroy
    # @no_use = NoUse.find(params[:id])
    # @no_use.destroy
    
    set_no_use(@no_use, User.current, false)

    # respond_to do |format|
      # format.html { redirect_to no_uses_url }
      # format.json { head :no_content }
    # end
  end
  private
  
  def find_no_use
    klass = Object.const_get(params[:object_type].camelcase) rescue nil
    if klass && klass.respond_to?('no_use_for')
      @no_use = klass.find_all_by_id(Array.wrap(params[:object_id]))
    end
    render_404 unless @no_use.present?
  end

  #flag标注功能，为1时设置‘没有帮助’，为0时设置取消
  def set_no_use(objects, user, flag)
    objects.each do |object|
      object.set_no_use(user, flag)
    end
    respond_to do |format|
      format.html { redirect_to_referer_or {render :text => (watching ? 'Watcher added.' : 'Watcher removed.'), :layout => true}}
      format.js { render :partial => 'set_no_use', :locals => {:user => user, :objects => objects} }
    end
  end
end
