package config

import (
	"bufio"
	"fmt"
	"os"
	"path/filepath"
	"strings"
)

const (
	defaultGnmiSubscriptionFilePath = "controller/configs/gNMISubscriptions.txt"
)

var gnmiSubscriptionPaths [][]string

// ReadGnmiSubscriptionPaths reads the paths the watcher should subscribe to provided in a file.
func ReadGnmiSubscriptionPaths() (err error) {
	var filePath string

	if GNMISubscriptionsFilePath != "" {
		filePath = GNMISubscriptionsFilePath
	} else {
		currentDir, err := os.Getwd()
		if err != nil {
			return err
		}

		filePath = filepath.Join(currentDir, defaultGnmiSubscriptionFilePath)
	}

	f, err := os.Open(filePath)
	if err != nil {
		return err
	}

	defer func() {
		if ferr := f.Close(); ferr != nil {
			fErrString := ferr.Error()
			err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString)
		}
	}()

	scanner := bufio.NewScanner(f)

	for scanner.Scan() {
		path := strings.Split(scanner.Text(), "/")
		gnmiSubscriptionPaths = append(gnmiSubscriptionPaths, path)
	}

	fmt.Println(gnmiSubscriptionPaths)

	return nil
}

// GetGnmiSubscriptionPaths returns the paths the watcher should subscribe to.
func GetGnmiSubscriptionPaths() [][]string {
	return gnmiSubscriptionPaths
}
