package services import ( "os" "path/filepath" "strings" "time" "voicesnap/internal/userdict" "github.com/wailsapp/wails/v3/pkg/application" ) // UserDictService exposes user dictionary management to the frontend. type UserDictService struct { store *userdict.Store app *application.App win application.Window } func NewUserDictService(store *userdict.Store) *UserDictService { return &UserDictService{store: store} } // SetApp sets the Wails app and parent window used for native dialogs. func (s *UserDictService) SetApp(app *application.App, win application.Window) { s.app = app s.win = win } // GetAll returns all replacement entries. func (s *UserDictService) GetAll() []userdict.Entry { return s.store.GetAll() } // Add creates a replacement entry. func (s *UserDictService) Add(from, to string) (userdict.Entry, error) { return s.store.Add(from, to) } // Update modifies an existing replacement entry. func (s *UserDictService) Update(id int64, from, to string, enabled bool) (userdict.Entry, error) { return s.store.Update(id, from, to, enabled) } // Delete removes an entry by id. func (s *UserDictService) Delete(id int64) { s.store.Delete(id) } // ClearAll removes all entries. func (s *UserDictService) ClearAll() { s.store.ClearAll() } // ExportJSON returns the full userdict.json payload. func (s *UserDictService) ExportJSON() string { return s.store.ExportJSON() } // ExportToFile asks the user where to save userdict.json, writes it, and returns the path. func (s *UserDictService) ExportToFile() (string, error) { if s.app == nil { return "", os.ErrInvalid } home, _ := os.UserHomeDir() dialog := s.app.Dialog.SaveFile(). SetMessage("导出用户词库"). SetButtonText("导出"). SetDirectory(filepath.Join(home, "Downloads")). SetFilename("userdict-"+time.Now().Format("20060102-1504")+".json"). AddFilter("JSON Files", "*.json"). CanCreateDirectories(true) if s.win != nil { dialog.AttachToWindow(s.win) } path, err := dialog.PromptForSingleSelection() if err != nil { return "", err } if path == "" { return "", nil } if strings.TrimSpace(filepath.Ext(path)) == "" { path += ".json" } if err := os.WriteFile(path, []byte(s.store.ExportJSON()), 0644); err != nil { return "", err } return path, nil } // ImportJSON replaces the dictionary from a JSON payload. func (s *UserDictService) ImportJSON(content string) error { return s.store.ImportJSON(content) } // GetPath returns the local userdict.json path. func (s *UserDictService) GetPath() string { return s.store.Path() }