package domain

import (
	"crypto/md5"
	"path/filepath"
	"strings"
)

type File struct {
	Language            Language
	baseFileName        string
	contentBaseName     string
	dir                 string
	ext                 string
	filename            string
	logicalName         string
	path                string
	translationBaseName string
	uniqueId            string
}

func NewFile(path string) File {
	out := File{
		Language:            LanguageUnd,
		baseFileName:        "",
		contentBaseName:     "",
		dir:                 filepath.Dir(path) + string(filepath.Separator),
		ext:                 strings.TrimPrefix(filepath.Ext(path), "."),
		filename:            path,
		logicalName:         filepath.Base(path),
		path:                path,
		translationBaseName: "",
		uniqueId:            "",
	}
	out.baseFileName = strings.TrimSuffix(out.logicalName, filepath.Ext(out.logicalName))

	parts := strings.Split(out.baseFileName, ".")
	out.Language = NewLanguage(parts[len(parts)-1])
	out.translationBaseName = strings.Join(parts[:len(parts)-1], ".")
	out.contentBaseName = out.translationBaseName

	switch out.translationBaseName {
	default:
		out.contentBaseName = out.translationBaseName
	case "_index", "index":
		out.contentBaseName = filepath.Base(out.dir)
	}

	hash := md5.New()
	_, _ = hash.Write([]byte(out.path))
	out.uniqueId = string(hash.Sum(nil))

	return out
}

// BaseFileName returns file name without extention.
func (f File) BaseFileName() string {
	return f.baseFileName
}

func (f File) ContentBaseName() string {
	return f.contentBaseName
}

// Dir returns directory path.
func (f File) Dir() string {
	return f.dir
}

// Ext returns file extention.
func (f File) Ext() string {
	return f.ext
}

func (f File) Filename() string {
	return f.filename
}

func (f File) LogicalName() string {
	return f.logicalName
}

func (f File) Path() string {
	return f.path
}

func (f File) TranslationBaseName() string {
	return f.translationBaseName
}

func (f File) UniqueID() string {
	return f.uniqueId
}
