package storage

import (
	"sync"

	"github.com/qdm12/gluetun/internal/models"
)

type Storage struct {
	mergedServers models.AllServers
	mergedMutex   sync.RWMutex
	// this is stored in memory to avoid re-parsing
	// the embedded JSON file on every call to the
	// SyncServers method.
	hardcodedServers models.AllServers
	logger           Logger
	filepath         string
}

type Logger interface {
	Info(s string)
	Warn(s string)
}

// New creates a new storage and reads the servers from the
// embedded servers file and the file on disk.
// Passing an empty filepath disables the reading and writing of
// servers.
func New(logger Logger, filepath string) (storage *Storage, err error) {
	// A unit test prevents any error from being returned
	// and ensures all providers are part of the servers returned.
	hardcodedServers, _ := parseHardcodedServers()

	storage = &Storage{
		hardcodedServers: hardcodedServers,
		mergedServers:    hardcodedServers,
		logger:           logger,
		filepath:         filepath,
	}

	if filepath != "" {
		if err := storage.syncServers(); err != nil {
			return nil, err
		}
	}

	return storage, nil
}
