package notmuch

import (
	"log"
	"strconv"
	"strings"
	"os/exec"
)

const (
	notmuchCmd = "notmuch"
	unreadThreadCountArgs = "count --output=threads tag:unread"
	unreadMessageCountArgs = "count --output=messages tag:unread"
)

type Notmuch struct {
}

func NewNotmuch(_ string) *Notmuch {
	return &Notmuch{}
}

func notmuchMust(options []string) string {
	cmd := exec.Command(notmuchCmd, options...)
	b, err := cmd.Output()
	if err != nil {
		log.Fatalf("Failed to read from process %v: %s\n", cmd, err)
	}

	return string(b)
}

func intFromCommand(options string) int {
	output := notmuchMust(strings.Fields(options))
	cnt, err := strconv.Atoi(strings.TrimSpace(output))
	if err != nil {
		log.Fatalf("Failed to parse int from %q: %s\n", output, err)
	}
	return cnt
}

func (nm *Notmuch) UnreadMessageCount() int {
	return intFromCommand(unreadMessageCountArgs)
}

func (nm *Notmuch) UnreadThreadCount() int {
	return intFromCommand(unreadThreadCountArgs)
}
