package imap

import (
	"context"
	"io"
	"log"

	imapbackend "github.com/emersion/go-imap/backend"
	imapserver "github.com/emersion/go-imap/server"

	"ur.gs/crockery/internal/store"
)

type Server interface {
	Run()

	io.Closer
}

func NewServer(cancel context.CancelFunc, datastore store.Interface, starttls bool) Server {
	out := &concrete{
		cancel:   cancel,
		store:    datastore,
		starttls: starttls,
	}

	out.server = imapserver.New(out)
	out.server.TLSConfig = out.store.TLSConfig()

	if starttls {
		out.server.Addr = ":143"
	} else {
		out.server.Addr = ":993"
	}

	return out
}

type concrete struct {
	cancel   context.CancelFunc
	store    store.Interface
	server   *imapserver.Server
	starttls bool
}

func (c *concrete) Run() {
	var err error

	if c.starttls {
		err = c.server.ListenAndServe()
	} else {
		err = c.server.ListenAndServeTLS()
	}

	if err != nil {
		log.Printf("Error serving IMAP %s: %v", c.server.Addr, err)
	} else {
		log.Printf("Stopped listening on IMAP %s", c.server.Addr)
	}

	c.cancel()
}

// backend implementation for go-smtp
func (c *concrete) Login(string, string) (imapbackend.User, error) {
	return nil, nil
}

func (c *concrete) Close() error {
	c.cancel() // FIXME: this doesn't touch the server

	return nil
}
