package main

import (
	"flag"
	"fmt"
	"net/http"
	"net/textproto"
	"os"
	"time"

	xprometheus "xinu.tv/imapstore/prometheus"
	"xinu.tv/lorem"

	"github.com/golang/glog"
	"github.com/jordwest/imap-server"
	"github.com/jordwest/imap-server/mailstore"
	"github.com/prometheus/client_golang/prometheus"
)

var (
	imapAddr = flag.String("imap", ":10143", "listen address for IMAP")
	httpAddr = flag.String("http", ":10080", "listen address for HTTP")
	msgCount = flag.Int("msg", 0, "number of messages to generate and insert in to mailstore")
)

func fill(ms mailstore.Mailstore, numMessages int) error {
	glog.Infof("Generation of %d messages started...", numMessages)
	defer glog.Infof("Done creating fake messages")
	genEmail := func() string {
		return lorem.Words(1, false) + "@" + lorem.Words(1, false) + ".com"
	}
	u, err := ms.Authenticate("username", "password")
	if err != nil {
		return err
	}
	mBoxes := u.Mailboxes()
	for i := 0; i < numMessages; i++ {
		mBox := mBoxes[i%len(mBoxes)]
		msg := mBox.NewMessage()
		date := time.Unix(int64(i)*17*24*60*60, 0).Format(time.RFC822Z)
		msg.SetHeaders(textproto.MIMEHeader{
			"Subject": []string{lorem.Sentence()},
			"From":    []string{genEmail()},
			"To":      []string{genEmail()},
			"Date":    []string{date},
		}).SetBody(lorem.Paragraph())
		if _, err := msg.Save(); err != nil {
			return fmt.Errorf("creating %d message in %s failed; %v", i, mBox.Name())
		}
	}
	return nil
}

func main() {
	flag.Parse()
	defer glog.Flush()

	http.Handle("/metrics", prometheus.Handler())
	go func() {
		glog.Fatal(http.ListenAndServe(*httpAddr, nil))
	}()

	var store mailstore.Mailstore
	store = mailstore.NewDummyMailstore()
	if *msgCount != 0 {
		if err := fill(store, *msgCount); err != nil {
			glog.Errorf("Failed to fill dummy mailstore: %v", err)
		}
	}
	store = xprometheus.NewMailstore(store)
	s := imap.NewServer(store)
	s.Transcript = os.Stdout
	s.Addr = *imapAddr

	if err := s.ListenAndServe(); err != nil {
		fmt.Printf("Error creating test connection: %s\n", err)
	}
}
