// package mock_store -- мок-хранилище для тестов
package mock_store

import (
	"fmt"
	"strings"

	"git.p78su.freemyip.com/svi/gostore/pkg/types"
)

var (
	IsBad_ = false // Для тестов
)

// MockStore -- мок-хранилище для тестов
type MockStore struct {
	serv types.IService
	dict map[string][]byte
}

// NewMockStore -- возвращает мок-хранилище для тестов
func NewMockStore(serv types.IService) (*MockStore, error) {
	if IsBad_ {
		return nil, fmt.Errorf("NewMockStore(): IsBad_==true")
	}
	if serv == nil {
		return nil, fmt.Errorf("NewMockStore(): serv==nil")
	}
	sf := &MockStore{
		serv: serv,
		dict: make(map[string][]byte),
	}
	return sf, nil
}

func (sf *MockStore) Put(key string, val []byte) error {
	if IsBad_ {
		return fmt.Errorf("MockStore.Put(): IsBad_==true")
	}
	if key == "" {
		return fmt.Errorf("MockStore.Put(): key is empty")
	}
	sf.dict[key] = val
	return nil
}

func (sf *MockStore) Get(key string) ([]byte, error) {
	if IsBad_ {
		return nil, fmt.Errorf("MockStore.Get(): IsBad_==true")
	}
	if key == "" {
		return nil, fmt.Errorf("MockStore.Get(): key is empty")
	}
	if val, ok := sf.dict[key]; ok {
		return val, nil
	}
	return nil, fmt.Errorf("MockStore.Get(): key not found")
}

func (sf *MockStore) Find(prefix string) ([]string, error) {
	if IsBad_ {
		return nil, fmt.Errorf("MockStore.Find(): IsBad_==true")
	}
	lstKey := []string{}
	for key := range sf.dict {
		if strings.HasPrefix(key, prefix) {
			lstKey = append(lstKey, key)
		}
	}
	return lstKey, nil
}

func (sf *MockStore) Del(key string) error {
	if IsBad_ {
		return fmt.Errorf("MockStore.Del(): IsBad_==true")
	}
	delete(sf.dict, key)
	return nil
}
