package imap

import (
	"fmt"
	"log"

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

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

var (
	ErrNotImplemented = fmt.Errorf("Not yet implemented")
)

// type Session implements the User interface for emersion/go-imap
type Session struct {
	ID          uint64
	Account     store.Account
	ServiceName string

	store store.Interface
}

func (s *Session) Username() string {
	return s.Account.Username
}

func (s *Session) ListMailboxes(subscribed bool) ([]imapbackend.Mailbox, error) {
	mailboxes, err := s.store.FindMailboxes(s.Account)
	log.Printf("Session(%v).ListMailboxes(%v): %#v %#v", s.ID, subscribed, mailboxes, err)

	if err != nil {
		return nil, err
	}

	imapped := make([]imapbackend.Mailbox, len(mailboxes))
	for i, mailbox := range mailboxes {
		imapped[i] = &Mailbox{stored: mailbox, session: s}
	}

	return imapped, nil
}

func (s *Session) GetMailbox(name string) (imapbackend.Mailbox, error) {
	mailbox, err := s.store.FindMailbox(s.Account, name)
	log.Printf("Session(%v).GetMailbox(%v): %#v %#v", s.ID, name, mailbox, err)
	if err != nil {
		return nil, err
	}

	return &Mailbox{stored: mailbox, session: s}, nil
}

func (s *Session) CreateMailbox(name string) error {
	log.Printf("Session(%v).CreateMailbox(%v): not implemented", s.ID, name)
	return ErrNotImplemented
}

func (s *Session) DeleteMailbox(name string) error {
	log.Printf("Session(%v).DeleteMailbox(%v): not implemented", s.ID, name)
	return ErrNotImplemented
}

func (s *Session) RenameMailbox(existingName, newName string) error {
	log.Printf("Session(%v).DeleteMailbox(%v, %v): not implemented", s.ID, existingName, newName)
	return ErrNotImplemented
}

func (s *Session) Logout() error {
	log.Printf("Ending %s session %d for %s", s.ServiceName, s.ID, s.Username())

	return nil
}
