package store

import (
	"errors"
)

type MailboxInterface interface {
	CreateMailbox(*Mailbox) error
	FindMailbox(account Account, name string) (Mailbox, error)
	FindMailboxes(account Account) ([]Mailbox, error)
}

type Mailbox struct {
	ID      uint64 `storm:"id,increment"`
	Account string `storm:"index"` // FK accounts.username
	Name    string `storm:"index"`
}

func (c *concrete) CreateMailbox(mailbox *Mailbox) error {
	return c.storm.Save(mailbox)
}

func (c *concrete) FindMailbox(account Account, name string) (Mailbox, error) {
	// FIXME I don't know how to storm
	candidates, err := c.FindMailboxes(account)
	if err != nil {
		return Mailbox{}, err
	}

	for _, mbox := range candidates {
		if mbox.Name == name {
			return mbox, nil
		}
	}

	return Mailbox{}, errors.New("not found")
}

func (c *concrete) FindMailboxes(account Account) ([]Mailbox, error) {
	var out []Mailbox

	return out, c.storm.Find("Account", account.Username, &out)
}
