module Keys
  class PoolsController < Keys::BaseController
    def index
      authorize Pool

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

      @pool = Pool.new

      resp = Pool.all(cursor, current_user.ldap_login)
      unless resp.success? && resp.status == 200
        flash[:error] = 'Error loading key pools'
        return
      end

      @pools = resp.body['key_pools']
      @cursor = resp.body['cursor']
    end

    def create
      authorize Pool

      @pool = Pool.new
      permitted = params.require(:keys_pool).permit(:pool_id, :product_type, :sku, :redemption_mode, :description, :handler_group_id, :start_date, :end_date).merge(ldap_login: current_user.ldap_login)
      @pool.attributes = permitted

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

      flash[:success] = 'Successfully created pool'

      redirect_back
    end

    def deactivate
      authorize Pool

      permitted = params.permit(:pool_id).merge(ldap_login: current_user.ldap_login)
      @pool = Pool.from_attributes(permitted)
      resp = @pool.update_status('INACTIVE')

      unless resp.success? && resp.status == 200
        flash[:error] = 'Error deactivating pool'
        return redirect_back
      end

      flash[:success] = 'Successfully deactivated pool'

      redirect_back
    end

    def activate
      authorize Pool

      permitted = params.permit(:pool_id).merge(ldap_login: current_user.ldap_login)
      @pool = Pool.from_attributes(permitted)
      resp = @pool.update_status('ACTIVE')

      unless resp.success? && resp.status == 200
        flash[:error] = 'Error activating pool'
        return redirect_back
      end

      flash[:success] = 'Successfully activated pool'

      redirect_back
    end
  end
end