class Admin::ModuleAppsNewInterfaceController < OrbitBackendController
  before_filter :check_auth
  # before_filter :authenticate_user!
  # before_filter :is_admin?
  include AdminHelper

  layout "new_admin"
  
  def check_auth

    unless is_admin? and is_manager?
      flash[:error] = "unauthorized access"
      if request.env["HTTP_REFERER"]
        redirect_to :back
      else
        render(:file => File.join(Rails.root, 'public/403.html'), :status => 403, :layout => false)
      end
      false
    end
  end

  def setting
    @sys_users = User.all(conditions: {admin: false}).includes(:avatar).not_guest_user
    @module_app = ModuleApp.find(params[:module_app_id])
    @options_from_collection_for_select_bulletin_categorys = [@module_app].collect{|ma| [ma.title,ma.id] }
    # if params.has_key? :category
    #   @bulletin_category = BulletinCategory.find params[:category][:id]
    # else
    #   @bulletin_category =  @bulletin_categorys.first
    # end
    @users_array = @module_app.managing_users rescue []

    respond_to do |format|
      format.html
      format.js
    end
  end
  
  def update_setting
    module_app = update_setting_by_params
    if module_app.save!
      flash[:notice] = t('update.success_')
    else
      flash[:notice] = t('update.fail')
    end
  end
  
  def user_list
    @module_app = ModuleApp.find params[:module_app][:id]
  end

  protected
  def update_setting_by_params
    user_sat = []
    ma = ModuleApp.find params[:module_app][:id]
    user_sat += User.find params[:users].keys if params.has_key?('users')
    users_to_new = user_sat - ma.managing_users
    users_to_remove = ma.managing_users - user_sat

    users_to_new.each do |new_user|
      ma.assign_manager(new_user,current_user)
    end

    users_to_remove.each do |remove_user|
      ma.remove_manager(remove_user)
    end
    ma
  end
  
  def get_categorys(id = nil)
    @bulletin_categorys = []
    if(is_manager? || is_admin?)
      @bulletin_categorys = (id ? BulletinCategory.find(id).to_a : BulletinCategory.all)
    elsif is_sub_manager?
      @bulletin_categorys = BulletinCategory.authed_for_user(current_user,'submit_new')
    end
  end



end