package adapters

import (
	"context"
	"strings"

	"github.com/tcolgate/hugot"
)

// Intercepts incoming messages. If they begin with a prefix, they are rewritten
// so they appear to be to the bot. For example, "!foo" would become "foo". The
// ToBot member of the Message struct is also set to true.
//
// The overall effect is to allow command handlers to be accessed via a !prefix
//
// You can also block the ubiquitous "help" handler outside of PMs by setting
// PrivateHelpOnly to true. This should really be a separate adapter, but
// overhead...
type PrefixAdapter struct {
	hugot.Adapter
	Prefix          string
	PrivateHelpOnly bool
	c               chan *hugot.Message
}

func NewPrefixAdapter(around hugot.Adapter, prefix string) *PrefixAdapter {
	return &PrefixAdapter{
		Adapter: around,
		Prefix:  prefix,
		c:       make(chan *hugot.Message),
	}
}

func (p *PrefixAdapter) Receive() <-chan *hugot.Message {
	return p.c
}

func (p *PrefixAdapter) Run(ctx context.Context) {
	for {
		select {
		case m := <-p.Adapter.Receive():
			if m == nil {
				return
			}
			// No use for this now, as we're using HearsHandler instead
			//m = p.fixup(m)
			if !p.isBlacklisted(m) {
				p.c <- m
			}
		case <-ctx.Done():
			return
		}
	}
}

func (p *PrefixAdapter) fixup(m *hugot.Message) *hugot.Message {
	if !m.ToBot && strings.HasPrefix(m.Text, p.Prefix) {
		m.Text = strings.Replace(m.Text, p.Prefix, "", 1)
		m.ToBot = true
	}

	return m
}

func (p *PrefixAdapter) isBlacklisted(m *hugot.Message) bool {
	return p.PrivateHelpOnly && m.ToBot && strings.HasPrefix(m.Text, "help") && !m.Private
}
