# frozen_string_literal: true

module Sass
  class Compiler
    class Session
      # The {FunctionRegistry} class.
      #
      # It stores sass custom functions and handles function calls.
      class FunctionRegistry
        attr_reader :compile_context, :global_functions

        def initialize(functions, session:)
          @compile_context = Object.new
          @global_functions = functions.keys.map!(&:to_s)
          @functions_by_name = functions.transform_keys do |signature|
            signature = signature.to_s
            index = signature.index('(')
            if index
              signature.slice(0, index)
            else
              signature
            end
          end

          @id = 0
          @functions_by_id = {}.compare_by_identity
          @ids_by_function = {}.compare_by_identity

          @session = session
        end

        def register(function)
          @ids_by_function.fetch(function) do |fn|
            id = @id
            @id = id.next

            @functions_by_id[id] = fn
            @ids_by_function[fn] = id
          end
        end

        def function_call(function_call_request)
          oneof = function_call_request.identifier
          identifier = function_call_request.public_send(oneof)
          function = case oneof
                     when :name
                       @functions_by_name[identifier]
                     when :function_id
                       @functions_by_id[identifier]
                     else
                       raise ArgumentError, "Unknown FunctionCallRequest.identifier #{identifier}"
                     end

          arguments = function_call_request.arguments.map do |argument|
            protofier.from_proto(argument)
          end

          success = protofier.to_proto(function.call(arguments))
          accessed_argument_lists = arguments.filter_map do |argument|
            if argument.is_a?(Sass::Value::ArgumentList) && argument.instance_variable_get(:@keywords_accessed)
              argument.instance_variable_get(:@id)
            end
          end

          EmbeddedProtocol::InboundMessage::FunctionCallResponse.new(
            id: function_call_request.id,
            success:,
            accessed_argument_lists:
          )
        rescue StandardError => e
          @session.backtrace = e.backtrace
          EmbeddedProtocol::InboundMessage::FunctionCallResponse.new(
            id: function_call_request.id,
            error: e.detailed_message(highlight: false)
          )
        end

        private

        def protofier
          @protofier ||= Protofier.new(self)
        end
      end

      private_constant :FunctionRegistry
    end
  end
end
