class Panel::News::BackEnd::NewsApprovalsController  < OrbitBackendController
  before_filter :authenticate_user!
  before_filter :is_admin?
  include AdminHelper
  
  def preview_and_approve
    @news_bulletin = NewsBulletin.find params[:news_bulletin_id]
  end
  
  def approve
    notice = ""
    @news_bulletin = NewsBulletin.find params[:news_bulletin_id]
    @news_bulletin.proc_check(params[:news_bulletin][:is_checked],params[:news_bulletin][:not_checked_reason])
    @news_bulletin.de_pending
     if @news_bulletin.save
        notice = t('approval.pass')
     else
        notice = t('approval.not_pass')
     end
    redirect_to(panel_news_back_end_news_bulletins_url,:notice => notice)
  end

  def setting
    @sys_users = User.all(conditions: {admin: false}).includes(:avatar)
    @news_bulletin_categorys = NewsBulletinCategory.all
    @options_from_collection_for_select_news_bulletin_categorys = @news_bulletin_categorys.collect{|bc| [bc.title,bc.id] }
    if params.has_key? :news_category
      @news_bulletin_categorys = NewsBulletinCategory.find params[:news_category][:id]
    else
      @news_bulletin_categorys =  @news_bulletin_categorys.first
    end  
    preload_object_auth = @news_bulletin_categorys.get_object_auth_by_title('fact_check')
    @users_array =  preload_object_auth.privilege_users rescue []
    respond_to do |format|
      format.html
      format.js
    end
  end
  
  def update_setting
    object_auth = update_setting_by_params
    if object_auth.save!
      flash[:notice] = t('update.success_')
    else
      flash[:notice] = t('update.fail')
    end
  end

  def user_list
    @news_bulletin_category = NewsBulletinCategory.find params[:news_category][:id]
  end

  protected
  def update_setting_by_params
    category = NewsBulletinCategory.find params[:news_category][:id]
    privilege_users = params[:users].collect{|key,value| User.find key }  rescue []
    object_auth_ary = category.object_auths.where(title: 'fact_check') || (category.object_auths.create :title=> 'fact_check')
    object_auth = object_auth_ary.first
    object_auth.privilege_users = privilege_users
    object_auth
  end

  def get_categorys(id = nil)
    @news_bulletin_categorys = []
    if(is_manager? || is_admin?)
      @news_bulletin_categorys = (id ? NewsBulletinCategory.find(id).to_a : NewsBulletinCategory.all)
    elsif is_sub_manager?
      @news_bulletin_categorys = NewsBulletinCategory.authed_for_user(current_user,'submit_new')
    end
  end
end
