module Keys
  class HandlerGroupsController < Keys::BaseController
    def index
      authorize HandlerGroup

      @handler_groups = []
      cursor = ''
      if params[:cursor].present?
        cursor = params[:cursor]
      end

      resp = HandlerGroup.all(cursor, current_user.ldap_login)

      unless resp.success? && resp.status == 200
        flash[:error] = 'Error loading handler groups'
        return
      end

      @handler_groups = resp.body['key_handler_groups']
      @cursor = resp.body['cursor']

      @handler_group = HandlerGroup.new
      if params[:handler_group_id].present?
        handler_group_id = params[:handler_group_id]
        resp = HandlerGroup.get(handler_group_id, current_user.ldap_login)

        unless resp.success? && resp.status == 200
          flash[:error] = 'Error searching handler group'
          return redirect_back
        end

        @handler_group.handler_group_id = resp.body['key_handler_group']['handler_group_id']
        @handler_group.description = resp.body['key_handler_group']['description']
        @handler_group.authorized_tuids_str = resp.body['key_handler_group']['authorized_tuids'].join("\n")

        @handler_group.authorized_tuids = resp.body['key_handler_group']['authorized_tuids']
        @handler_group.authorized_client_ids_str = resp.body['key_handler_group']['authorized_client_ids'].join("\n")
        @handler_group.authorized_client_ids = resp.body['key_handler_group']['authorized_client_ids']
      end
    end

    def create
      authorize HandlerGroup

      authorized_tuids = params[:keys_handler_group][:authorized_tuids_str].split("\n").collect {|u| u.strip || u }.uniq.sort
      authorized_client_ids = params[:keys_handler_group][:authorized_client_ids_str].split("\n").collect {|u| u.strip || u }.uniq.sort

      @handler_group = HandlerGroup.new
      permitted = params.require(:keys_handler_group).permit(:handler_group_id, :description).merge(ldap_login: current_user.ldap_login, authorized_client_ids: authorized_client_ids, authorized_tuids: authorized_tuids)
      @handler_group.attributes = permitted

      resp = @handler_group.create
      unless resp.success? && resp.status == 200
        flash[:error] = 'Error creating handler group'
        return redirect_back
      end

      flash[:success] = 'Successfully created handler group'

      redirect_back
    end
  end
end