class Panel::WebResource::BackEnd::WebLinksController < OrbitBackendController
  include OrbitControllerLib::DivisionForDisable
  before_filter :authenticate_user!
  # before_filter :for_app_manager,:except => [:index,:show] 
  before_filter :for_app_sub_manager,:except => [:index]
  before_filter :only => [ :new,:edit,:update] do |controller|
    controller.get_categorys('WebLinkCategory')
  end

  def index
  
  get_categorys("WebLinkCategory",params[:web_link_category_id])
  @filter = params[:filter]
  new_filter = params[:new_filter]

  if @filter && params[:clear]
    @filter.delete(params[:type])
  elsif @filter && new_filter
    if @filter.has_key?(new_filter[:type]) && @filter[new_filter[:type]].include?(new_filter[:id].to_s)
      @filter[new_filter[:type]].delete(new_filter[:id].to_s)
    elsif @filter.has_key?(new_filter[:type])
      @filter[new_filter[:type]] << new_filter[:id].to_s
    else
      @filter.merge!({new_filter[:type] => [new_filter[:id].to_s]})
    end
  elsif new_filter
    @filter = {new_filter[:type] => [new_filter[:id].to_s]}
  end
  @web_link_categories =  get_categories_for_index("WebLinkCategory")
  @web_link_category_ids = @web_link_categories.collect{|t| t.id.to_s} + [nil]

	# @web_links = WebLink.search(params[:category_id])
	#@web_links = (params[:sort] || @filter) ? get_sorted_and_filtered_web_links : WebLink.all.page(params[:page]).per(10)
  @web_links = (params[:sort] || @filter) ? get_sorted_and_filtered("web_link",:web_link_category_id.in => @web_link_category_ids) : get_viewable("web_link",:web_link_category_id.in => @web_link_category_ids)

  get_tags

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @web_links }
      format.js
    end
  end

  # GET /web_links/1
  # GET /web_links/1.xml
  def show
    @web_link = WebLink.find(params[:id])
    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @web_link }
    end
  end

  # GET /web_links/new
  # GET /web_links/new.xml
  def new
    @web_link = WebLink.new
    get_tags

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @web_link }
    end
  end

  # GET /web_links/1/edit
  def edit
    @web_link = WebLink.find(params[:id])
	get_tags
  end

  # POST /web_links
  # POST /web_links.xml
  def create
    @web_link = WebLink.new(params[:web_link])
	
    @web_link.create_user_id = current_user.id
    @web_link.update_user_id = current_user.id

    respond_to do |format|
      if @web_link.save
        format.html { redirect_to(panel_web_resource_back_end_web_links_url) }
        format.xml  { render :xml => @web_link, :status => :created, :location => @web_link }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @web_link.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /web_links/1
  # PUT /web_links/1.xml
  def update
    @web_link = WebLink.find(params[:id])
	
    @web_link.update_user_id = current_user.id
	
	params[:web_link][:tag_ids] ||=[]

    respond_to do |format|
      if @web_link.update_attributes(params[:web_link])
        format.html { redirect_to(panel_web_resource_back_end_web_links_url) }
		format.js  { render 'toggle_enable' }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @web_link.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /web_links/1
  # DELETE /web_links/1.xml
  def destroy
    @web_link = WebLink.find(params[:id])
    @web_link.destroy

    respond_to do |format|
      format.html { redirect_to(panel_web_resource_back_end_web_links_url) }
      # format.xml  { head :ok }
      format.js
    end
  end

  def delete
    if params[:to_delete]
      web_links = WebLink.any_in(:_id => params[:to_delete]).delete_all
    end
    redirect_to panel_web_resource_back_end_web_links_url(:direction => params[:direction], :sort => params[:sort], :sort_options => params[:sort_options])
  end
  
  protected
 

  # def get_index_categories(id = nil)
  #   @bulletin_categorys = []
  #   if(is_manager? || is_admin?)
  #     @bulletin_categorys = (id ? BulletinCategory.admin_manager_all.find(id).to_a : BulletinCategory.admin_manager_all)
  #   elsif is_sub_manager?
  #     @bulletin_categorys = BulletinCategory.all
  #   end
  #   @bulletin_categorys
  # end


  # def get_categorys(id = nil)
  #   @web_link_categorys = []
  #   if(is_manager? || is_admin?)
  #     @web_link_categorys = (id ? WebLinkCategory.admin_manager_all.find(id).to_a : WebLinkCategory.admin_manager_all))
  #   elsif is_sub_manager?
  #     @web_link_categorys = WebLinkCategory.all.authed_for_user(current_user,'edit')
  #   end
  #   if @web_link_categorys.empty? && params[:action] != "index"
  #       flash[:alert] = t("announcement.error.no_avilb_cate_for_posting")
  #       redirect_to :action => :index
  #   end
  # end
  
  def get_tags
  	module_app = ModuleApp.first(:conditions => {:key => 'web_resource'})
  	@tags = Tag.all(:conditions => {:module_app_id => module_app.id})
  end

  def get_sorted_and_filtered_web_links
    web_links = WebLink.all
    case params[:sort]
      when 'category'
        category_ids = web_links.distinct(:web_link_category_id)
        categories = WebLinkCategory.find(category_ids) rescue nil
        if categories
          h = Hash.new 
          categories.each { |category| h[category.i18n_variable[I18n.locale]] = category.id }
          sorted = params[:direction].eql?('asc') ? h.sort : h.sort.reverse!
          sorted_categorys = sorted.collect {|a| web_links.where(:web_link_category_id => a[1]).entries }
          web_links = sorted_categorys.flatten!
        end
      when 'name'
        h = Array.new 
        web_links.each { |web_link| h << [web_link.name[I18n.locale].downcase, web_link] }
        sorted = params[:direction].eql?('asc') ? h.sort : h.sort.reverse!
        web_links = sorted.collect {|a| a[1] }
      when 'status'
        web_links = web_links.order_by(:is_top, params[:direction]).order_by(:is_hot, params[:direction]).order_by(:is_hidden, params[:direction]).order_by(:is_pending, params[:direction]).order_by(:is_checked, params[:direction]).order_by(:is_rejected, params[:direction])
      when 'tags'
        a = Array.new
        WebResourceTag.all.order_by(I18n.locale, params[:direction]).each { |tag| a << tag.web_links }
        a.flatten!
        a.uniq!
        tmp = Array.new 
        web_links.where(:tag_ids => []).each { |web_link| tmp << [web_link.name[I18n.locale].downcase, web_link] }
        sorted = params[:direction].eql?('asc') ? tmp.sort : tmp.sort.reverse!
        sorted_names = sorted.collect {|a| a[1] }
        a = params[:direction].eql?('asc') ? (sorted_names + a) : (a + sorted_names)
        web_links = a.flatten
    end
    # if @filter
    #   @filter.each do |key, value|
    #     case key
    #       when 'status'
    #         a = Array.new
    #         web_links.each do |web_link|
    #           value.each do |v|
    #             case v
    #               when 'pending'
    #                 a << web_link if web_link.is_checked.nil?
    #               when 'rejected'
    #                 a << web_link if web_link.is_checked.eql?(false)
    #               else
    #                 a << web_link if web_link[v]
    #             end
    #           end
    #         end
    #         web_links = a.uniq
    #       when 'categories'
    #         a = Array.new
    #         web_links.each do |web_link|
    #           a << web_link if value.include?(web_link.web_link_category.id.to_s)
    #         end
    #         web_links = a.uniq
    #       when 'tags'
    #         a = Array.new
    #         web_links.each do |web_link|
    #           web_link.tags.each do |tag|
    #             a << web_link if value.include?(tag.id.to_s)
    #           end
    #         end
    #         web_links = a.uniq
    #     end if value.size > 0
    #   end
    # end
    Kaminari.paginate_array(web_links).page(params[:page]).per(10)
  end
  
end
