class Admin::CategoriesController < OrbitBackendController

  open_for_manager
   
  def index
    @categories = get_categories_for_index
    @categories = @categories.page(params[:page]).per(10)
  end

  def new
    @category = Category.new
    render layout: false
  end
  
  def edit
    @category = Category.find(params[:id])
    render layout: false
  end

  def create
    @category = @module_app.categories.build(params[:category])
    if @category.save
      redirect_to admin_module_app_categories_url(@module_app_id)
    else
      @category = Category.new(params[:category])
      flash.now[:error] = t('create.error.category')
      render action: :new
    end
  end

  def update
    @category = Category.find(params[:id])
    if @category.update_attributes(params[:category])
      redirect_to admin_module_app_categories_url(@module_app_id), :status => 303
    else
      flash.now[:error] = t('update.error.category')
      render action: :edit
    end
  end

  def toggle
    @category = Category.find(params[:id])
    @category.disable = @category.disable ? false : true
    @category.save!
    redirect_to action: :index 
  end

  # def get_categorys_json
  #   categorys = BulletinCategory.all
  #   data = Array.new

  #   categorys.each do |c|
  #     data << {
  #       category: c.title,
  #       # this is a json format
  #       # link: "http://#{request.host_with_port}#{panel_announcement_back_end_bulletin_category_get_bulletins_json_path(c)}"
  #       # remember to uncommand a rule in route.rb, too
  #       link: "#{url_for( :action => "index",
  #                         :controller => "panel/announcement/front_end/bulletins",
  #                         :format => :rss,
  #                         :only_path => false,
  #                         :inner=>true,
  #                         :category_id => c )}"
  #     }
  #   end

  #   #render :json => @data.to_json
  #   #to print readable json
  #   render :json => JSON.pretty_generate(data)
  # end

  # def get_bulletins_json
  #   bulletin = BulletinCategory.find(params[:bulletin_category_id]).bulletins
  #   p bulletin
  #   data = Array.new

  #   bulletin.each do |b|
  #     deadline = b.deadline

  #     if not deadline.nil?
  #       deadline = display_date_time(deadline)
  #     else
  #       deadline = I18n.t("no_deadline")
  #     end

  #     data << {
  #       title: b.title,
  #       link: "http://#{request.host_with_port}#{panel_announcement_front_end_bulletin_path(b, :category_id => b.bulletin_category.id)}",
  #       postdate: display_date_time(b.postdate),
  #       deadline: deadline,
  #       tag: b.sorted_tags.to_a,
  #     }
  #   end

  #   render :json => JSON.pretty_generate(data)
  # end

  private

  def setup_vars
    @module_app = ModuleApp.find(params[:module_app_id]) rescue nil
    raise ModuleAppError, 'Can not find ModuleApp' if @module_app.nil?
    @module_app_id = @module_app.id rescue nil
  end
  
end
