summaryrefslogtreecommitdiff
path: root/helpers.go
blob: e24aee3ece1ae6f54af2054db67f427e0f38ca63 (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
102
103
104
105
106
107
108
109
110
111
package chatpb

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

	"github.com/google/uuid"
	"go.wit.com/log"
	"google.golang.org/protobuf/proto"
	timestamppb "google.golang.org/protobuf/types/known/timestamppb"
)

func (c *Chats) AddGeminiComment(s string) *ChatEntry {
	chat := new(ChatEntry)

	chat.From = Who_GEMINI
	chat.Content = s
	chat.Ctime = timestamppb.New(time.Now())

	c.AppendNew(chat)

	return chat
}

func (c *Chats) AddUserComment(s string) *ChatEntry {
	chat := new(ChatEntry)

	chat.From = Who_USER
	chat.Content = s

	c.AppendNew(chat)

	return chat
}

func UnmarshalChats(data []byte) (*Chats, error) {
	c := new(Chats)
	err := c.Unmarshal(data)
	return c, err
}

func UnmarshalChatsTEXT(data []byte) (*Chats, error) {
	c := new(Chats)
	err := c.UnmarshalTEXT(data)
	return c, err
}

func (all *Chats) AddFile(filename string) error {
	// Nil checks for safety.
	if all == nil {
		return fmt.Errorf("cannot call AddFile on a nil *Chats object")
	}
	if all.Chats == nil {
		all.Chats = make([]*Chat, 0)
	}

	data, err := os.ReadFile(filename)
	if err != nil {
		log.Fatalf("Error reading file %s: %v", filename, err)
		return err
	}

	logData, err := UnmarshalChatsTEXT(data)
	if err != nil {
		log.Fatalf("Error unmarshaling log file %s: %v", filename, err)
		return err
	}

	// New, simplified logic assumes all files use the new nested format.
	for _, chatGroup := range logData.GetChats() {
		// It's now a direct append since the structure is the same.
		// We still clone to ensure the appended data is a safe copy.
		newChatGroup := proto.Clone(chatGroup).(*Chat)
		all.AppendByUuid(newChatGroup)
	}
	return nil
}

func (chats *Chats) VerifyUuids() bool {
	var changed bool

	all := chats.SortByUuid()
	for all.Scan() {
		chat := all.Next()
		if chat.Uuid == "" {
			chat.Uuid = uuid.New().String()
			changed = true
		}
	}
	return changed
}

func (c *Chat) VerifyUuid() bool {
	if c.Uuid == "" {
		c.Uuid = uuid.New().String()
		return true
	}
	return false
}

func (x *Chats) AppendNew(y *ChatEntry) {
	x.Lock()
	defer x.Unlock()

	var chat *Chat
	chat = proto.Clone(y).(*ChatEntry)

	x.Chats = append(x.Chats, chat)
}