require 'celluloid'
require 'thread'

module Celluloid
  require_relative './util/fiber_pool'

  class Task
    class PooledFiber < Fibered
      class << self
        def trim_size=(value)
          @trim_size = value
        end

        def global_trim_size=(value)
          @global_trim_size = value
        end

        def trim_size() @trim_size; end
        def global_trim_size() @global_trim_size; end

        def fiber_pool
          @fiber_pool ||= Util::FiberPool.new(trim_size, global_trim_size)
        end
      end

      def create
        queue = Thread.current[:celluloid_queue]
        actor_system = Thread.current[:celluloid_actor_system]
        @fiber = PooledFiber.fiber_pool.acquire do
          Thread.current[:celluloid_role] = :actor
          Thread.current[:celluloid_queue] = queue
          Thread.current[:celluloid_actor_system] = actor_system
          yield
        end
      end
    end

    # Reasonable defaults
    PooledFiber.trim_size = 64
    PooledFiber.global_trim_size = 30_000
    PooledFiber.global_trim_size = 2000 if RUBY_ENGINE == 'rbx'
  end
end
