class Panel::Announcement::BackEnd::BulletinsController < OrbitBackendController
  
  before_filter :authenticate_user!
  before_filter :is_admin?

  def index
    # @bulletins = Bulletin.all
    # @bulletins = Bulletin.desc("postdate desc")
	  get_categorys(params[:bulletin_category_id])
	  get_tags

    @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

    # @bulletins = Bulletin.where("bulletin_category_id" => params[:bulletin_category_id]).desc("postdate") if params[:bulletin_category_id]
    
  	# @bulletins = Bulletin.search(params[:search], params[:category_id])
    # @bulletins = Bulletin.all.order_by([params[:sort], params[:direction]])
    @bulletins = (params[:sort] || @filter) ? get_sorted_and_filtered_bulletins : Bulletin.all.page(params[:page]).per(10)
  	@bulletin_categories = BulletinCategory.all

    @bulletin_link = BulletinLink.new
    @link_url = panel_announcement_back_end_bulletins_path
	
    @bulletin_file = BulletinFile.new
    @file_url = panel_announcement_back_end_bulletins_path
	
    respond_to do |format|
      format.html # index.html.erb
      format.js { }
      format.xml  { render :xml => @bulletins }
    end
  end

  # GET /bulletins/1
  # GET /bulletins/1.xml
  def show
    @bulletin = Bulletin.find(params[:id])
	get_tags
	# get_categorys
	
    # @bulletin_categorys = BulletinCategory.where("_id" => params[:id])
	
    # if params[:id]
      # @bulletins = Bulletin.where("bulletin_category_id" => params[:id])
    # else
      # @bulletins = Bulletin.desc("postdate desc")
    # end

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

  # GET /bulletins/new
  # GET /bulletins/new.xml
  def new
    @bulletin = Bulletin.new
	
	@link_url = panel_announcement_back_end_bulletins_path
    
	# @bulletin.bulletin_files.build
	# @bulletin.bulletin_files.new
	
	get_categorys
	get_tags

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

  # GET /bulletins/1/edit
  def edit
    @bulletin = Bulletin.find(params[:id])
    # @summary_variable = @bulletin.summary_variable
	
	@link_url = panel_announcement_back_end_bulletin_path(@bulletin)
	
	get_categorys
	get_tags
  end

  # POST /bulletins
  # POST /bulletins.xml
  def create
	
	if params[:bulletin_link]
  
		@bulletin_link = BulletinLink.new(params[:bulletin_link])

		respond_to do |format|
		  if @bulletin_link.save
			format.js { render 'create_bulletin_link' }
		  end
		end
	
	elsif params[:bulletin_file]
  
		@bulletin_file = BulletinFile.new(params[:bulletin_file])

		respond_to do |format|
		  if @bulletin_file.save
			format.js { render 'create_bulletin_file' }
		  end
		end
	
	else  
  
		@bulletin = Bulletin.new(params[:bulletin])
		
		@bulletin.create_user_id = current_user.id
		@bulletin.update_user_id = current_user.id

		respond_to do |format|
		  if @bulletin.save
			# format.html { redirect_to(panel_announcement_back_end_bulletin_url(@bulletin), :notice => t('announcement.create_bulletin_success')) }
			format.html { redirect_to(panel_announcement_back_end_bulletins_url, :notice => t('announcement.create_bulletin_success')) }
			format.xml  { render :xml => @bulletin, :status => :created, :location => @bulletin }
			format.js
		  else
			format.html { render :action => "new" }
			format.xml  { render :xml => @bulletin.errors, :status => :unprocessable_entity }
		  end
		end
		
	end
	
  end

  def link_quick_add
	# debugger
    
    @bulletin_link = BulletinLink.new
	@link_url = panel_announcement_back_end_bulletins_path
	
	@bulletin_link.bulletin_id = params[:bulletin_id]
	
    respond_to do |format|
      format.js
    end
	
  end

  def link_quick_edit
	# debugger
    @bulletin_link = BulletinLink.find(params[:bulletin_id])
	
	@link_url = panel_announcement_back_end_bulletin_path(@bulletin_link)
	
    # @bulletin = Bulletin.find(params[:bulletin_id])
	
	# @link_url = panel_announcement_back_end_bulletin_path(@bulletin)
	
    respond_to do |format|
      format.js
    end
	
  end

  def file_quick_add
    # debugger
    
    @bulletin_file = BulletinFile.new
    @file_url = panel_announcement_back_end_bulletins_path
	
    @bulletin_file.bulletin_id = params[:bulletin_id]
	
    respond_to do |format|
      format.js
    end
	
  end

  def file_quick_edit
    # debugger
    @bulletin_file = BulletinFile.find(params[:bulletin_id])
	
    @file_url = panel_announcement_back_end_bulletin_path(@bulletin_file)
	
    respond_to do |format|
      format.js
    end
  end

  # PUT /bulletins/1
  # PUT /bulletins/1.xml
  def update
	
  	if params[:bulletin_link]
  	
  		@bulletin_link = BulletinLink.find(params[:id])
  		
  		@link_url = panel_announcement_back_end_bulletin_path(@bulletin_link)

  		respond_to do |format|
  		  if @bulletin_link.update_attributes(params[:bulletin_link])
  			# format.html { redirect_to(panel_announcement_back_end_bulletins_url) }
  			format.js { render 'update_bulletin_link' }
  		  end
  		end
  	
  	elsif params[:bulletin_file]
  	
  		@bulletin_file = BulletinFile.find(params[:id])
  		
  		@file_url = panel_announcement_back_end_bulletin_path(@bulletin_file)

  		respond_to do |format|
  		  if @bulletin_file.update_attributes(params[:bulletin_file])
  			# format.html { redirect_to(panel_announcement_back_end_bulletins_url) }
  			format.js { render 'update_bulletin_file' }
  		  end
  		end
  	
  	else
    
  		@bulletin = Bulletin.find(params[:id])
  		
  		@bulletin.update_user_id = current_user.id
  		
  		# @bulletin.image.clear if params[:bulletin][:image_del] == '1'
  		# if params[:bulletin][:image_del] == '1' 
  			# @bulletin.remove_image!
  			# @bulletin.image_del = nil
  			# params[:bulletin][:image_del] = nil
  		# end

  		respond_to do |format|
  		  if @bulletin.update_attributes(params[:bulletin]) && @bulletin.save
  			# format.html { redirect_to(panel_announcement_back_end_bulletin_url(@bulletin), :notice => t('bulletin.update_bulletin_success')) }
  			format.html { redirect_to(panel_announcement_back_end_bulletins_url, :notice => t('bulletin.update_bulletin_success')) }
  			format.js  { render 'toggle_enable' }
  			format.xml  { head :ok }
  		  else
  			format.html { render :action => "edit" }
  			format.xml  { render :xml => @bulletin.errors, :status => :unprocessable_entity }
  		  end
  		end
		
    end
	
  end

  # DELETE /bulletins/1
  # DELETE /bulletins/1.xml
  def destroy
    @bulletin = Bulletin.find(params[:id])
    # @bulletin.bulletin_files.destroy
    @bulletin.destroy

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

  # def top_edit
	
	# Bulletin.where(id: params[:id]).update_all( is_top: true )
    # respond_to do |format|
      # format.html { redirect_to(panel_announcement_back_end_bulletins_url) }
      # format.xml  { head :ok }
    # end
	
  # end
  

  def load_quick_edit
    @bulletin = Bulletin.find(params[:id])
    @type = params[:type]
    @bulletin_categories = BulletinCategory.all
    get_tags
  end

  def delete
    if params[:to_delete]
      bulletins = Bulletin.any_in(:_id => params[:to_delete]).delete_all
    end
    redirect_to panel_announcement_back_end_bulletins_url(:filter => params[:filter], :direction => params[:direction], :sort => params[:sort])
  end

  
  protected
  
  def get_categorys(id = nil)
    @bulletin_categorys = []
    if(is_manager? || is_admin?)
      @bulletin_categorys = (id ? BulletinCategory.find(id).to_a : BulletinCategory.excludes('disabled' => true))
    elsif is_sub_manager?
      @bulletin_categorys = BulletinCategory.authed_for_user(current_user,'submit_new')
    end
  end
  
  def get_tags
  	module_app = ModuleApp.first(:conditions => {:key => 'announcement'})
  	@tags = Tag.all(:conditions => {:module_app_id => module_app.id}).order_by(I18n.locale, :asc)
  end

  def get_sorted_and_filtered_bulletins
    bulletins = Bulletin.all
    case params[:sort]
      when 'postdate', 'deadline'
        bulletins = bulletins.order_by([params[:sort], params[:direction]])
      when 'category'
        category_ids = bulletins.distinct(:bulletin_category_id)
        categories = BulletinCategory.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| bulletins.where(:bulletin_category_id => a[1]).entries }
          bulletins = sorted_categorys.flatten!
        end
      when 'title'
        h = Array.new 
        bulletins.each { |bulletin| h << [bulletin.title[I18n.locale].downcase, bulletin] }
        sorted = params[:direction].eql?('asc') ? h.sort : h.sort.reverse!
        bulletins = sorted.collect {|a| a[1] }
      when 'status'
        bulletins = bulletins.order_by(:is_top, params[:direction]).order_by(:is_hot, params[:direction]).order_by(:is_hidden, params[:direction])
      when 'update_user_id'
        user_ids = bulletins.distinct(:update_user_id)
        users = User.find(user_ids) rescue nil
        if users
          h = Array.new 
          users.each { |user| h << [user.name, user.id] }
          sorted = params[:direction].eql?('asc') ? h.sort : h.sort.reverse!
          sorted_users = sorted.collect {|a| bulletins.where(:update_user_id => a[1]).entries }
          bulletins = sorted_users.flatten
        end
      when 'tags'
        a = Array.new
        AnnouncementTag.all.order_by(I18n.locale, params[:direction]).each { |tag| a << tag.bulletins }
        a.flatten!
        a.uniq!
        tmp = Array.new 
        bulletins.where(:tag_ids => []).each { |bulletin| tmp << [bulletin.title[I18n.locale].downcase, bulletin] }
        sorted = params[:direction].eql?('asc') ? tmp.sort : tmp.sort.reverse!
        sorted_titles = sorted.collect {|a| a[1] }
        a = params[:direction].eql?('asc') ? (sorted_titles + a) : (a + sorted_titles)
        bulletins = a.flatten
     end
    if @filter
      @filter.each do |key, value|
        case key
          when 'status'
            a = Array.new
            bulletins.each do |bulletin|
              value.each do |v|
                a << bulletin if bulletin[v]
              end
            end
            bulletins = a
          when 'categories'
            a = Array.new
            bulletins.each do |bulletin|
              a << bulletin if value.include?(bulletin.bulletin_category.id.to_s)
            end
            bulletins = a
          when 'tags'
            a = Array.new
            bulletins.each do |bulletin|
              bulletin.tags.each do |tag|
                a << bulletin if value.include?(tag.id.to_s)
              end
            end
            bulletins = a
        end if value.size > 0
      end
    end
    Kaminari.paginate_array(bulletins).page(params[:page]).per(10)
  end
  
end
