// Copyright 2022 schukai GmbH
// SPDX-License-Identifier: AGPL-3.0

package configuration

import (
	"bytes"
	"github.com/stretchr/testify/assert"
	"path"
	"testing"
	"time"
)

type ConfigIssue1SubStruct struct {
	DA PathValue `yaml:"DA"`
}

type ConfigIssue1Struct struct {
	A string                `yaml:"A"`
	B PathValue             `yaml:"B"`
	C PathValue             `yaml:"C"`
	D ConfigIssue1SubStruct `yaml:"D"`
}

func addSampleIssue1() {

	e := &mockFile{}

	content := []byte(
		`---
A: "Hello!"
B: "/tmp"
C: "xyz.html"
D:
    DA: "tmp.xyz"
...

`)

	e.buffer = bytes.NewBuffer(content)

	e.FileInfo = mockFileInfo{
		name: "test",
		size: int64(len(content)),
		mode: 0,
		mod:  time.Now(),
		dir:  false,
		sys:  nil,
	}

	fileSamples = append(fileSamples, fileSample{
		file: e,
	})

}

func TestIssue1(t *testing.T) {

	fileSamples = []fileSample{}
	defer func() { fileSamples = nil }()

	addSampleIssue1()

	defaults := ConfigIssue1Struct{}

	mockFs := mockFS{}

	c := New(defaults)
	c.SetMnemonic("test")
	c.SetFileFormat(Yaml)
	c.SetFilesystem(mockFs)

	// setDefaultdirectories can be returned errors
	c.SetDefaultDirectories().ResetErrors()
	c.Import()

	if c.HasErrors() {
		t.Error("Expected not error", c.Errors())
	}

	assert.Equal(t, c.Config().A, "Hello!")
	assert.Equal(t, c.Config().B, PathValue("/tmp"))

	if !path.IsAbs(string(c.Config().C)) {
		t.Error("Expected absolute path got ", c.Config().C)
	}

	if !path.IsAbs(string(c.Config().D.DA)) {
		t.Error("Expected absolute path got ", c.Config().D.DA)
	}

}