class Panel::News::BackEnd::NewsBulletinsController < OrbitBackendController
  include OrbitControllerLib::DivisionForDisable

#  before_filter :for_admin_only,:only => [:]
#  before_filter :for_app_manager,:only => [:index,:show,] 
  before_filter :force_order_for_visitor,:only=>[:index,:show,:get_sorted_and_filtered_news_bulletins]
  before_filter :force_order_for_user,:except => [:index,:show,:get_sorted_and_filtered_news_bulletins]
  before_filter :for_app_sub_manager,:except => [:index,:show,:get_sorted_and_filtered_news_bulletins]
  before_filter :only => [ :new,:edit,:update,:create] do |controller|
    controller.get_categorys('NewsBulletinCategory') 
    controller.get_unit_list
  end
  before_filter :clean_values, :only => [:create, :update]

  def preview
    #@preview_obj = Preview.create(:object=>params[:news_bulletin],:expired_at=>DateTime.now+30.minutes,:preview_at_link=>"panel_news_front_end_news_bulletin_path",:object_class_type=>"NewsBulletin")
    news_bulletin = NewsBulletin.new params
    @preview_obj = news_bulletin.to_preview
    @preview_obj.save
    render '/shared/preview/preview.html.erb', :layout=>false
  end

  def index
    # @news_bulletins = NewsBulletin.all
    # @news_bulletins = NewsBulletin.desc("postdate desc")
	  get_categorys("NewsBulletinCategory",params[:news_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

    # @news_bulletins = NewsBulletin.where("news_bulletin_category_id" => params[:news_bulletin_category_id]).desc("postdate") if params[:news_bulletin_category_id]
    
  	# @news_bulletins = NewsBulletin.search(params[:search], params[:category_id])
    # @news_bulletins = NewsBulletin.all.order_by([params[:sort], params[:direction]])


    # @news_bulletins = (params[:sort] || @filter) ? get_sorted_and_filtered_news_bulletins : NewsBulletin.all.page(params[:page]).per(10)

    @news_bulletin_categories = get_categories_for_index("NewsBulletinCategory")
    @news_bulletin_category_ids = @news_bulletin_categories.collect{|t| t.id.to_s} + [nil]


    @news_bulletins = (params[:sort] || @filter) ? get_sorted_and_filtered("news_bulletin",:news_bulletin_category_id.in => @news_bulletin_category_ids) : get_viewable("news_bulletin",:news_bulletin_category_id.in => @news_bulletin_category_ids)

    @news_bulletin_link = NewsBulletinLink.new
    @link_url = panel_news_back_end_news_bulletins_path

    @news_bulletin_file = NewsBulletinFile.new
    @file_url = panel_news_back_end_news_bulletins_path
	
    respond_to do |format|
      format.html # index.html.erb
      format.js { }
      format.xml  { render :xml => @news_bulletins }
    end
  end

  # GET /news_bulletins/1
  # GET /news_bulletins/1.xml
  def show
    @news_bulletin = NewsBulletin.find(params[:id])
	get_tags
	# get_categorys
	
    # @news_bulletin_categorys = NewsBulletinCategory.where("_id" => params[:id])
	
    # if params[:id]
      # @news_bulletins = NewsBulletin.where("news_bulletin_category_id" => params[:id])
    # else
      # @news_bulletins = NewsBulletin.desc("postdate desc")
    # end

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

  # GET /news_bulletins/new
  # GET /news_bulletins/new.xml
  def new
    if(session[:in_validate_object].blank?)
      @news_bulletin = NewsBulletin.new
    else
      @news_bulletin = session[:in_validate_object]
      session[:in_validate_object] = {}
    end
    @link_url = panel_news_back_end_news_bulletins_path
    
	# @news_bulletin.news_bulletin_files.build
	# @news_bulletin.news_bulletin_files.new

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

  # GET /news_bulletins/1/edit
  def edit
    @news_bulletin = NewsBulletin.find(params[:id])
    if !current_user.admin? && (@news_bulletin.is_rejected? || @news_bulletin.is_checked?)
      redirect_to :action => :index
    else
      # @summary_variable = @news_bulletin.summary_variable
  	
    	@link_url = panel_news_back_end_news_bulletin_path(@news_bulletin)
    	
    	get_tags
    end
  end

  # POST /news_bulletins
  # POST /news_bulletins.xml
  def create
    get_tags

	if params[:news_bulletin_link]
  
		@news_bulletin_link = NewsBulletinLink.new(params[:news_bulletin_link])

		respond_to do |format|
		  if @news_bulletin_link.save
			format.js { render 'create_news_bulletin_link' }
		  end
		end
	
	elsif params[:news_bulletin_file]
  
		@news_bulletin_file = NewsBulletinFile.new(params[:news_bulletin_file])

		respond_to do |format|
		  if @news_bulletin_file.save
                  expire_page(:controller=>'panel/news/widget/news_bulletins' , :action=>'home_banner')
			format.js { render 'create_news_bulletin_file' }
		  end
		end
	
	else  
  
		@news_bulletin = NewsBulletin.new(params[:news_bulletin])
            @news_bulletin.deadline = nil if (@news_bulletin.deadline < @news_bulletin.postdate rescue nil)
		
		@news_bulletin.create_user_id = current_user.id
		@news_bulletin.update_user_id = current_user.id

            if(is_manager? || is_admin?)
                    @news_bulletin.is_checked = true
                    @news_bulletin.is_rejected = false
                    @news_bulletin.de_pending
            end

		respond_to do |format|
		  if @news_bulletin.save
                  expire_page(:controller=>'panel/news/widget/news_bulletins' , :action=>'home_banner')
			format.html { redirect_to(panel_news_back_end_news_bulletins_url, :notice => t('news_bulletin.create_news_bulletin_success')) }
			format.xml  { render :xml => @news_bulletin, :status => :created, :location => @news_bulletin }
                  format.js 
                   #format.json {render :json => {"success"=>"true","redirect_url"=>panel_news_back_end_news_bulletins_url,"notice" => t('news_bulletin.create_news_bulletin_success')}}
		  else
			format.html { render :action => "new" }
			format.xml  { render :xml => @news_bulletin.errors, :status => :unprocessable_entity }
		  end
		end
		
	end
	
  end

  def link_quick_add
	# debugger
    
    @news_bulletin_link = NewsBulletinLink.new
	@link_url = panel_news_back_end_news_bulletins_path
	
	@news_bulletin_link.news_bulletin_id = params[:news_bulletin_id]
	
    respond_to do |format|
      format.js
    end
	
  end

  def link_quick_edit
	# debugger
    @news_bulletin_link = NewsBulletinLink.find(params[:news_bulletin_id])
	
	@link_url = panel_news_back_end_news_bulletin_path(@news_bulletin_link)
	
    # @news_bulletin = NewsBulletin.find(params[:news_bulletin_id])
	
	# @link_url = panel_news_back_end_news_bulletin_path(@news_bulletin)
	
    respond_to do |format|
      format.js
    end
	
  end

  def file_quick_add
    # debugger
    
    @news_bulletin_file = NewsBulletinFile.new
    @file_url = panel_news_back_end_news_bulletins_path
	
    @news_bulletin_file.news_bulletin_id = params[:news_bulletin_id]
	
    respond_to do |format|
      format.js
    end
	
  end

  def file_quick_edit
    # debugger
    @news_bulletin_file = NewsBulletinFile.find(params[:news_bulletin_id])
	
    @file_url = panel_news_back_end_news_bulletin_path(@news_bulletin_file)
	
    respond_to do |format|
      format.js
    end
  end

  # PUT /news_bulletins/1
  # PUT /news_bulletins/1.xml
  def update
  	if params[:news_bulletin_link]
  	
  		@news_bulletin_link = NewsBulletinLink.find(params[:id])
  		
  		@link_url = panel_news_back_end_news_bulletin_path(@news_bulletin_link)

  		respond_to do |format|
  		  if @news_bulletin_link.update_attributes(params[:news_bulletin_link])
                  expire_page(:controller=>'panel/news/widget/news_bulletins' , :action=>'home_banner')
  			# format.html { redirect_to(panel_news_back_end_news_bulletins_url) }
  			format.js { render 'update_news_bulletin_link' }
  		  end
  		end
  	
  	elsif params[:news_bulletin_file]
  	
  		@news_bulletin_file = NewsBulletinFile.find(params[:id])
  		
  		@file_url = panel_news_back_end_news_bulletin_path(@news_bulletin_file)

  		respond_to do |format|
  		  if @news_bulletin_file.update_attributes(params[:news_bulletin_file])
                  expire_page(:controller=>'panel/news/widget/news_bulletins' , :action=>'home_banner')
  			# format.html { redirect_to(panel_news_back_end_news_bulletins_url) }
  			format.js { render 'update_news_bulletin_file' }
  		  end
  		end
  	
  	else
    
  		@news_bulletin = NewsBulletin.find(params[:id])
            @news_bulletin.deadline = nil if (@news_bulletin.deadline < @news_bulletin.postdate rescue nil)
  		
  		@news_bulletin.update_user_id = current_user.id
  		
  		# @news_bulletin.image.clear if params[:news_bulletin][:image_del] == '1'
  		# if params[:news_bulletin][:image_del] == '1' 
  			# @news_bulletin.remove_image!
  			# @news_bulletin.image_del = nil
  			# params[:news_bulletin][:image_del] = nil
  		# end
            delete_out_invalid_date_from_params
  		respond_to do |format|
  		  if @news_bulletin.update_attributes(params[:news_bulletin])
                  if(is_manager? || is_admin?)
                    @news_bulletin.is_checked = true
                    @news_bulletin.is_rejected = false
                    @news_bulletin.de_pending!
                 end
                  expire_page(:controller=>'panel/news/widget/news_bulletins' , :action=>'home_banner')
  			# format.html { redirect_to(panel_news_back_end_news_bulletin_url(@news_bulletin), :notice => t('news_bulletin.update_news_bulletin_success')) }
  			format.html { redirect_to(panel_news_back_end_news_bulletins_url, :notice => t('update.success_')) }
  			format.js  { render 'toggle_enable' }
  			format.xml  { head :ok }
  		  else
          get_tags
          
  			format.html { render :action => "edit" }
  			format.xml  { render :xml => @news_bulletin.errors, :status => :unprocessable_entity }
  		  end
  		end
		
    end
	
  end

  # DELETE /news_bulletins/1
  # DELETE /news_bulletins/1.xml
  def destroy
    @news_bulletin = NewsBulletin.find(params[:id])
    # @news_bulletin.news_bulletin_files.destroy
    @news_bulletin.destroy

    respond_to do |format|
      expire_page(:controller=>'panel/news/widget/news_bulletins' , :action=>'home_banner')
      format.html { redirect_to(panel_news_back_end_news_bulletins_url) }
      # format.xml  { head :ok }
      format.js
    end
  end

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

  def load_quick_edit
    @news_bulletin = NewsBulletin.find(params[:id])
    @type = params[:type]
    @news_bulletin_categories = NewsBulletinCategory.all
        #TODO 需要做 manager ,admin 才可以 all.  其他 available就好

    get_tags
  end

  def delete
    if params[:ids]
      news_bulletins = NewsBulletin.any_in(:_id => params[:ids]).delete_all
    end
    redirect_to panel_news_back_end_news_bulletins_url(:filter => params[:filter], :direction => params[:direction], :sort => params[:sort], :sort_options => params[:sort_options])
  end

  
  protected

  def delete_out_invalid_date_from_params
    if((params[:news_bulletin]["deadline(1i)"] && params[:news_bulletin]["deadline(1i)"].blank?) or (params[:news_bulletin]["deadline(2i)"] && params[:news_bulletin]["deadline(2i)"].blank?) or (params[:news_bulletin]["deadline(3i)"] && params[:news_bulletin]["deadline(3i)"].blank?)) 
      params[:news_bulletin].delete("deadline(1i)")
      params[:news_bulletin].delete("deadline(2i)")
      params[:news_bulletin].delete("deadline(3i)")
      @news_bulletin.deadline = nil
    end rescue nil
  end
  
  # def get_categories_for_index(id = nil)
  #   @news_bulletin_categories = []
  #   if(is_manager? || is_admin?)
  #     @news_bulletin_categories = (id ? NewsBulletinCategory.admin_manager_all.find(id).to_a : NewsBulletinCategory.admin_manager_all)
  #   elsif is_sub_manager?
  #     @news_bulletin_categories = NewsBulletinCategory.all
  #   end
  #   @news_bulletin_categories
  # end

  # def get_categorys(id = nil)
  #   @news_bulletin_categorys = []
  #   @unit_list_for_anc = UnitListForAnc.all
  #   if(is_manager? || is_admin?)
  #     @news_bulletin_categorys = (id ? NewsBulletinCategory.admin_manager_all.find(id).to_a : NewsBulletinCategory.admin_manager_all)
  #   elsif is_sub_manager?
  #     @news_bulletin_categorys = NewsBulletinCategory.all.authed_for_user(current_user,'submit')
  #   end
  #    if @news_bulletin_categorys.empty? && params[:action] != "index"
  #        flash[:alert] = t("news_bulletin.error.no_avilb_cate_for_posting")
  #        redirect_to :action => :index
  #    end
  # end
  def get_unit_list
        @unit_list_for_anc = UnitListForAnc.all
  end
  
  def get_tags
  	module_app = ModuleApp.first(:conditions => {:key => 'news'})
  	@tags = Tag.all(:conditions => {:module_app_id => module_app.id}).order_by(I18n.locale, :asc) rescue []
  end

  def clean_values
    if params[:news_bulletin]
      params[:news_bulletin][:news_bulletin_links_attributes].each_with_index do |link, index|
        params[:news_bulletin][:news_bulletin_links_attributes].delete(index.to_s) if link[1]['url'].blank? and link[1]['title'].blank?
      end rescue nil
      params[:news_bulletin][:news_bulletin_files_attributes].each_with_index do |link, index|
        params[:news_bulletin][:news_bulletin_files_attributes].delete(index.to_s) if link[1]['file'].blank? and link[1]['title'].blank?
      end rescue nil
    end
  end

end
