class Admin::AuthorizationsController < OrbitBackendController

  prepend_before_filter :admin_or_manager
   
  def index
    @module_apps ||= ModuleApp.any_of({is_authorizable: true}, {is_approvable: true}).order_by([:title, :asc])
    if @module_apps && @module_apps.include?(@module_app)
      if @type
        case @type
        when 'category_authorization', 'category_approval'
          if @module_app.has_category
            @objects = @module_app.categories
          else
            @error = t(:no_category)
          end
        else
          @objects = @klass.all
        end
        unless @objects.blank?
          @object ||= @objects.first
          @users = @object.get_authorization_by_title("#{@type}_#{@module_app.key}").authorized_users rescue nil
        else
          @error = t(:no_data)
        end
      else
        @users = @module_app.managers
      end
    elsif @module_apps
      @module_app = @module_apps.first
      redirect_to admin_authorizations_url(@module_app.key)
    else
      redirect_to :root
    end
  end

  def add_roles
    roles = Role.find(params[:role_ids]) rescue nil
    unless roles.nil?
      authorization = get_or_create_authorization
      add_roles_to_auth(authorization, roles)
    end
    @users = authorization.authorized_users
    render 'admin/authorizations/reload_users'
  end

  def add_sub_roles
    sub_roles = SubRole.find(params[:sub_role_ids]) rescue nil
    unless sub_roles.nil?
      authorization = get_or_create_authorization
      add_sub_roles_to_auth(authorization, sub_roles)
    end
    @users = authorization.authorized_users
    render 'admin/authorizations/reload_users'
  end

  def add_users
    users = User.find(params[:user_ids]) rescue nil
    unless users.nil?
      authorization = get_or_create_authorization
      add_users_to_auth(authorization, users)
    end
    @users = authorization.authorized_users
    render 'admin/authorizations/reload_users'
  end

  def modal_select
    existing_users = User.find(params[:ids]) rescue []
    roles = Role.all
    if @type
      @object_id = @object.id if @object
      @sorted_users = roles.inject({}) do |users, role|
        users[role] = role.users.where(admin: false) - existing_users - @module_app.managers
        users
      end
    else
      @sorted_users = roles.inject({}) do |users, role|
        users[role] = role.users.where(admin: false) - existing_users
        users
      end
    end
  end

  def remove_roles
    roles = Role.find(params[:role_ids]) rescue []
    unless roles.blank?
      authorization = get_or_create_authorization
      remove_roles_form_auth(authorization, roles)
    end
    @users = authorization.authorized_users
    render 'admin/authorizations/reload_users'
  end

  def remove_sub_roles
    sub_roles = SubRole.find(params[:sub_role_ids]) rescue []
    unless sub_roles.blank?
      authorization = get_or_create_authorization
      remove_sub_roles_from_auth(authorization, sub_roles)
    end
    @users = authorization.authorized_users
    render 'admin/authorizations/reload_users'
  end

  def remove_users
    @users = User.find(params[:ids]) rescue []
    unless @users.blank?
      authorization = get_or_create_authorization
      remove_users_from_auth(authorization, @users)
    end
    @users = authorization.authorized_users
    render 'admin/authorizations/reload_users'
  end
  
  protected

  def add_roles_to_auth(authorization, roles)
    authorization.add_roles(roles)
  end

  def add_sub_roles_to_auth(authorization, sub_roles)
    authorization.add_sub_roles(sub_roles)
  end

  def add_users_to_auth(authorization, users)
    authorization.add_users(users)
  end

  def get_or_create_authorization
    case @type
    when 'category_approval'
      if @object
        @object.auth_approval || @object.create_auth_approval(module_app_id: @module_app.id, title: "#{@type}_#{@module_app.key}")
      else
        @error = t(:no_data)
      end
    when 'category_authorization'
      if @object
        @object.auth_sub_manager || @object.create_auth_sub_manager(module_app_id: @module_app.id, title: "#{@type}_#{@module_app.key}")
      else
        @error = t(:no_data)
      end
    when nil
      @module_app.auth_manager || @module_app.create_auth_manager(module_app_id: @module_app.id, title: @module_app.key)
    else
      auth = @object.get_authorization_by_title("#{@type}_#{@module_app.key}")
      unless auth
        auth = @object.create_auth_approval(module_app_id: @module_app.id, title: "#{@type}_#{@module_app.key}") if @type.include?('approval')
        auth = @object.create_auth_sub_manager(module_app_id: @module_app.id, title: "#{@type}_#{@module_app.key}") if @type.include?('authorization')
      end
      auth
    end
  end

  def remove_roles_form_auth(authorization, roles)
    authorization.remove_roles(roles)
  end

  def remove_sub_roles_from_auth(authorization, sub_roles)
    authorization.remove_sub_roles(sub_roles)
  end

  def remove_users_from_auth(authorization, users)
    authorization.remove_users(users)
  end

  private

  def admin_or_manager
    @override_can_use = true
    setup_vars   
    authenticate_user!
    user_is_manager?
  end

  def setup_vars
    @module_app = ModuleApp.first(conditions: {:key => params[:module]} ) if params[:module]
    @type = params[:type].underscore if params[:type]
    if @type
      @klass = @type.gsub('_authorization', '').gsub('_approval', '').classify.constantize rescue nil
      @object = @klass.find(params[:id]) rescue nil
    end
  end

  def user_is_manager?
    unless is_admin?
      @module_apps = current_user.managed_module_apps
      redirect_to :root if @module_apps.blank?
    end
  end
end
