// Copyright 2024 Matthew Rich <matthewrich.conf@gmail.com>. All rights reserved.
package resource

import (
	_ "context"
	"encoding/json"
	"github.com/stretchr/testify/assert"
	"net/url"
	"testing"
)

func TestNewResourceTypes(t *testing.T) {
	resourceTypes := NewTypes()
	assert.NotEqual(t, nil, resourceTypes)
}

func TestNewResourceTypesRegister(t *testing.T) {
	m := NewFooResource()

	resourceTypes := NewTypes()
	assert.NotEqual(t, nil, resourceTypes)

	resourceTypes.Register("foo", func(*url.URL) Resource { return m })

	r, e := resourceTypes.New("foo://")
	assert.Equal(t, nil, e)
	assert.Equal(t, m, r)
}

func TestResourceTypesFromURI(t *testing.T) {
	m := NewFooResource()

	resourceTypes := NewTypes()
	assert.NotEqual(t, nil, resourceTypes)

	resourceTypes.Register("foo", func(*url.URL) Resource { return m })

	r, e := resourceTypes.New("foo://bar")
	assert.Equal(t, nil, e)
	assert.Equal(t, m, r)

}

func TestResourceTypesHasType(t *testing.T) {
	m := NewFooResource()

	resourceTypes := NewTypes()
	assert.NotNil(t, resourceTypes)

	resourceTypes.Register("foo", func(*url.URL) Resource { return m })

	assert.True(t, resourceTypes.Has("foo"))
}

func TestResourceTypeName(t *testing.T) {
	type fooResourceName struct {
		Name TypeName `json:"type"`
	}
	fooTypeName := &fooResourceName{}
	jsonType := `{ "type": "file" }`
	e := json.Unmarshal([]byte(jsonType), &fooTypeName)
	assert.Nil(t, e)
	assert.Equal(t, "file", string(fooTypeName.Name))
}
