// Author: Matthew Shiel
// Code adapted from https://github.com/kennysong/goeliza/

package eliza

import (
	"fmt"
	"math/rand"
	"regexp"
	"strings"
	"time"
)

type InteractiveBot interface {
	ReplyTo(statement string) string
}

type BotPersonality struct {
	Personality *Personality
}

func NewBotPersonality(personality *Personality) *BotPersonality {
	return &BotPersonality{personality}

}

// Greetings will return a random introductory sentence for ELIZA.
func (p *BotPersonality) Greetings() string {
	return p.randChoice(p.Personality.Introductions)
}

// GoodbyeResponse will return a random goodbye sentence for ELIZA.
func (p *BotPersonality) GoodbyeResponse() string {
	return p.randChoice(p.Personality.Goodbyes)
}

// ReplyTo will construct a reply for a given statement using ELIZA's rules.
func (p *BotPersonality) ReplyTo(statement string) string {
	// First, preprocess the statement for more effective matching
	statement = p.preprocess(statement)

	// Then, we check if this is a quit statement
	if p.IsQuitStatement(statement) {
		return p.GoodbyeResponse()
	}

	// Next, we try to match the statement to a statement that ELIZA can
	// recognize, and construct a pre-determined, appropriate response.
	for pattern, responses := range p.Personality.Psychobabble {
		re := regexp.MustCompile(pattern)
		matches := re.FindStringSubmatch(statement)

		// If the statement matched any recognizable statements.
		if len(matches) > 0 {
			// If we matched a regex group in parentheses, get the first match.
			// The matched regex group will match a "fragment" that will form
			// part of the response, for added realism.
			var fragment string
			if len(matches) > 1 {
				fragment = p.reflect(matches[1])
			}

			// Choose a random appropriate response, and format it with the
			// fragment, if needed.
			response := p.randChoice(responses)
			if strings.Contains(response, "%s") {
				response = fmt.Sprintf(response, fragment)
			}
			fmt.Printf("For Statement \"%s\" got a hit with pattern \"%s\" Responded With \"%s\"\n", statement, pattern, response)
			return response
		}
	}

	// If no patterns were matched, return a default response.
	return p.randChoice(p.Personality.DefaultResponses)
}

// IsQuitStatement returns if the statement is a quit statement
func (p *BotPersonality) IsQuitStatement(statement string) bool {
	statement = p.preprocess(statement)
	for _, quitResponse := range p.Personality.QuitResponses {
		if statement == quitResponse {
			return true
		}
	}
	return false
}

// preprocess will do some normalization on a statement for better regex matching
func (p *BotPersonality) preprocess(statement string) string {
	statement = strings.TrimRight(statement, "\n.!")
	statement = strings.ToLower(statement)
	return statement
}

// reflect flips a few words in an input fragment (such as "I" -> "you").
func (p *BotPersonality) reflect(fragment string) string {
	words := strings.Split(fragment, " ")
	for i, word := range words {
		if reflectedWord, ok := p.Personality.ReflectedWords[word]; ok {
			words[i] = reflectedWord
		}
	}
	return strings.Join(words, " ")
}

// randChoice returns a random element in an (string) array.
func (p *BotPersonality) randChoice(list []string) string {
	// Added for truly random generation of numbers with seeds
	if len(list) == 0 {
		return ""
	}
	rand.Seed(time.Now().UnixNano())
	randIndex := rand.Intn(len(list))
	return list[randIndex]
}