package store

import (
	"net/mail"

	"github.com/asdine/storm/q"
)

type MessageInterface interface {
	CreateMessage(Message) error
	FindMessages(Mailbox) ([]Message, error)

	// if end == 0, it means "from start to most recent"
	FindMessagesInRange(mailbox Mailbox, start, end uint64) ([]Message, error)
}

type Message struct {
	// FIXME: this should be per-mailbox, IMAP "only" allows 32-bit message UIDs?
	ID uint64 `storm:"id,increment"`

	Mailbox uint64 `storm:"index"` // FK mailbox.id

	Header mail.Header // The parsed headers
	EML    []byte      // The full email, unaltered
}

func (c *concrete) CreateMessage(message Message) error {
	return c.storm.Save(&message)
}

func (c *concrete) FindMessages(mailbox Mailbox) ([]Message, error) {
	var out []Message

	return out, c.storm.Find("Mailbox", mailbox.ID, &out)
}

func (c *concrete) FindMessagesInRange(mailbox Mailbox, start, end uint64) ([]Message, error) {
	var out []Message

	matchers := []q.Matcher{
		q.Eq("Mailbox", mailbox.ID),
		q.Gte("ID", start),
	}

	if end > 0 {
		matchers = append(matchers, q.Lte("ID", end))
	}

	return out, c.storm.Select(matchers...).Find(&out)
}
