package container

import (
	"fmt"
	"testing"
)

func TestHandlerManager_New(t *testing.T) {
	handler := NewElementHandler(elementInstance)
	handlerMapping := map[Interface]ComponentHandler{testElementType: handler}
	handlerManager, err := NewHandlerManager(handlerMapping)
	if err != nil {
		t.Fatalf("意外错误:%s", err.Error())
	}
	if handlerManager == nil {
		t.Fatalf("创建失败!")
	}
	if handlerManager.handlerMapping == nil {
		t.Fatalf("组件句柄映射设置错误!")
	}
	if len(handlerManager.handlerMapping) != 1 {
		t.Fatalf("组件句柄映射数量错误!")
	}
	handler1, ok := handlerManager.handlerMapping[testElementType]
	if !ok {
		t.Fatalf("未找到组件句柄!")
	}
	if handler != handler1 {
		t.Fatalf("组件句柄错误!")
	}
}

func TestHandlerManager_New_NullInterfaceType(t *testing.T) {
	handler := NewElementHandler(elementInstance)
	_, err := NewHandlerManager(map[Interface]ComponentHandler{nil: handler})
	if err == nil {
		t.Fatalf("意外的没有错误!")
	}
	if err.Error() != fmt.Sprintf("组件接口不能为空!") {
		t.Fatalf("意外错误:%s", err.Error())
	}
}

func TestHandlerManager_New_NullHandler(t *testing.T) {
	_, err := NewHandlerManager(map[Interface]ComponentHandler{testElementType: nil})
	if err == nil {
		t.Fatalf("意外的没有错误!")
	}
	if err.Error() != fmt.Sprintf("组件句柄不能为空!") {
		t.Fatalf("意外错误:%s", err.Error())
	}
}

func TestHandlerManager_Handler(t *testing.T) {
	handlerManager, err := NewHandlerManager(map[Interface]ComponentHandler{})
	if err != nil {
		t.Fatalf("意外错误:%s", err.Error())
	}
	handler := NewElementHandler(elementInstance)
	handlerManager.handlerMapping[testElementType] = handler
	if handlerManager.Handler(testElementType) != handler {
		t.Fatalf("获取指定组件句柄错误!")
	}
	if handlerManager.Handler(testServiceType) != nil {
		t.Fatalf("获取不存在的组件句柄错误!")
	}
}

func TestHandlerManager_Handler__NullInterfaceType(t *testing.T) {
	handlerManager, err := NewHandlerManager(map[Interface]ComponentHandler{})
	if err != nil {
		t.Fatalf("意外错误:%s", err.Error())
	}
	if handlerManager.Handler(nil) != nil {
		t.Fatalf("获取空接口类型的组件句柄错误!")
	}
}
