package story_service

import (
	"encoding/json"
	"os"
	"strings"
)

var (
	replaceMap = map[string]string{
		"a": "а",
		"e": "е",
		"o": "о",
		"c": "с",
		"p": "р",
		"x": "х",
		"y": "у",
		"k": "к",
		"m": "м",
		"t": "т",
		"h": "н",
		"b": "в",
		"u": "и",
	}
)

type Story struct {
	Places []*Place `json:"places"`
}

type Place struct {
	Code         string         `json:"code"`
	Name         string         `json:"name"`
	Text         string         `json:"text"`
	Applications []*Application `json:"applications"`
}

type Application struct {
	Name string `json:"name"`
}

type StoryService struct {
	story *Story
}

func NewStoryService() (*StoryService, error) {
	data, err := os.ReadFile("./story/story.json")
	if err != nil {
		return nil, err
	}
	story := &Story{}
	if err := json.Unmarshal(data, story); err != nil {
		return nil, err
	}
	return &StoryService{story: story}, nil
}

func (s *StoryService) GetPlace(code string) *Place {
	code = clearCode(code)
	for _, place := range s.story.Places {
		if clearCode(place.Code) == code {
			return place
		}
	}
	return &Place{
		Code: code,
		Name: "Не найдено",
		Text: "Такой точки не существует.",
	}
}

func clearCode(code string) string {
	code = strings.ToLower(code)
	code = strings.ReplaceAll(code, "-", "")
	for latin, cyrillic := range replaceMap {
		code = strings.ReplaceAll(code, latin, cyrillic)
	}
	return code
}
