package store

import (
	"bytes"
	"io"
	"io/ioutil"
	"log"
	"net/mail"
)

type SpoolInterface interface {
	SpoolMessage([]Account, io.Reader) error
}

// FIXME: we don't actually spool for now, we just store it to each user's
// mailbox. This might lead to oddness in the partial delivery case.
func (c *concrete) SpoolMessage(recipients []Account, r io.Reader) error {
	data, err := ioutil.ReadAll(r)
	if err != nil {
		return err
	}

	message, err := mail.ReadMessage(bytes.NewReader(data))
	if err != nil {
		return err
	}

	for _, recipient := range recipients {
		message := Message{
			Mailbox: recipient.DefaultMailbox,
			Header:  message.Header,
			EML:     data,
		}

		log.Printf("Creating email: %#v", message)
		log.Print(string(data))

		if err := c.CreateMessage(message); err != nil {
			return err
		}
	}

	return nil
}
