summaryrefslogtreecommitdiff
path: root/add.go
blob: 9d25288bf16fd5375a982c7d2d4326bf844ea653 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package main

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net/http"
	"strings"

	tea "github.com/charmbracelet/bubbletea"
)

const apiVersion = 6

type addNote struct {
	Action  string        `json:"action"`
	Version int           `json:"version"`
	Params  addNoteParams `json:"params"`
}

type addNoteParams struct {
	Note note `json:"note"`
}

type note struct {
	DeckName  string `json:"deckName"`
	ModelName string `json:"modelName"`
	// Fields will not be trivial to generalize
	Fields  fields  `json:"fields"`
	Options options `json:"options"`
}

type fields struct {
	Front string `json:"Front"`
	Back  string `json:"Back"`
}

type options struct {
	AllowDuplicate bool   `json:"allowDuplicate"`
	DuplicateScope string `json:"duplicateScope"`
}

func addCard(c *http.Client, apiURL, deckName, modelName, front, back string) tea.Cmd {
	return func() tea.Msg {
		front = strings.TrimSpace(front)
		if back == "" {
			return errMsg(errors.New("definition is blank"))
		}
		if front == "" {
			return errMsg(errors.New("word is blank"))
		}

		noteRequest := addNote{
			Action:  "addNote",
			Version: apiVersion,
			Params: addNoteParams{
				Note: note{
					DeckName:  deckName,
					ModelName: modelName,
					Fields: fields{
						Front: front,
						Back:  back,
					},
					Options: options{
						AllowDuplicate: false,
						DuplicateScope: "deck",
					},
				},
			},
		}

		jsonBytes, err := json.Marshal(noteRequest)
		if err != nil {
			return errMsg(fmt.Errorf("marshaling JSON: %s", err))
		}

		req, err := http.NewRequest("POST", apiURL, bytes.NewBuffer(jsonBytes))
		req.Header.Set("Content-Type", "application/json")

		resp, err := c.Do(req)
		if err != nil {
			return errMsg(fmt.Errorf("making request: %s", err))
		}
		defer resp.Body.Close()

		body, _ := io.ReadAll(resp.Body)

		var jsonResp struct {
			Error string `json:"error"`
		}

		json.Unmarshal(body, &jsonResp)
		if jsonResp.Error != "" {
			return errMsg(fmt.Errorf("creating card: %s", jsonResp.Error))
		}

		return wordAddedMsg(front)
	}
}