package main

import (
	"errors"
	"fmt"
	"os"
	"path/filepath"

	"github.com/kirsle/configdir"
)

const (
	packageName = "dev.lmika.dequoter"
)

type Store struct {
	storeDir           string
	currentBufferIndex int
}

func NewStore() (*Store, error) {
	cfgDir := configdir.LocalConfig(packageName)
	if err := os.MkdirAll(cfgDir, 0755); err != nil {
		return nil, err
	}

	return &Store{
		storeDir:           cfgDir,
		currentBufferIndex: 0,
	}, nil
}

func (s *Store) LoadBuffer() (string, error) {
	return s.loadBuffer(fmt.Sprintf("%02d", s.currentBufferIndex))
}

func (s *Store) SaveBuffer(buffer string) error {
	return s.saveBuffer(fmt.Sprintf("%02d", s.currentBufferIndex), buffer)
}

func (s *Store) loadBuffer(name string) (string, error) {
	bfrFilename := filepath.Join(s.storeDir, fmt.Sprintf("%s.buffer", name))
	bts, err := os.ReadFile(bfrFilename)
	if err != nil {
		if errors.Is(err, os.ErrNotExist) {
			return "", nil
		}
		return "", err
	}

	return string(bts), err
}

func (s *Store) saveBuffer(name string, buffer string) error {
	bfrFilename := filepath.Join(s.storeDir, fmt.Sprintf("%s.buffer", name))
	return os.WriteFile(bfrFilename, []byte(buffer), 0644)
}
