// Copyright 2015 Light Code Labs, LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package conffile

import (
	"errors"
	"fmt"
	"io"
	"net"
	"os"
	"path/filepath"
	"strings"
	"time"

	"codeberg.org/miekg/dns/cmd/atomdns/internal/iface"
)

// Dispenser is a type that dispenses tokens, similarly to a lexer, except that it can do so with some
// notion of structure and has some really convenient methods.
type Dispenser struct {
	filename string
	keys     []string
	tokens   []Token
	cursor   int
	nesting  int
	handlers []string // previous handlers seen by this handler
}

func NewTestDispenser(input string) Dispenser {
	tokens, _ := allTokens(strings.NewReader(input))
	return Dispenser{
		filename: "Testfile",
		tokens:   tokens,
		cursor:   -1,
	}
}

// newDispenser returns a Dispenser, ready to use for parsing the given input.
func newDispenser(filename string, input io.Reader) Dispenser {
	tokens, _ := allTokens(input)
	return Dispenser{
		filename: filename,
		tokens:   tokens,
		cursor:   -1,
	}
}

// NewDispenser returns a Dispenser filled with the given tokens.
func NewDispenser(filename string, keys []string, tokens []Token, handlers []string) Dispenser {
	return Dispenser{
		filename: filename,
		keys:     keys,
		tokens:   tokens,
		cursor:   -1,
		handlers: handlers,
	}
}

// Handlers returns all previous handlers seen up until the parsing of this handler. The current handler's
// name is included in the list.
func (d *Dispenser) Handlers() []string { return d.handlers }

// Next loads the next token. Returns true if a token was loaded; false otherwise. If false, all tokens
// have been consumed.
func (d *Dispenser) Next() bool {
	if d.cursor < len(d.tokens)-1 {
		d.cursor++
		return true
	}
	return false
}

// NextArg loads the next token if it is on the same line. Returns true if a token was loaded; false
// otherwise. If false, all tokens on the line have been consumed. It handles imported tokens correctly.
func (d *Dispenser) NextArg() bool {
	if d.cursor < 0 {
		d.cursor++
		return true
	}
	if d.cursor >= len(d.tokens) {
		return false
	}
	if d.cursor < len(d.tokens)-1 &&
		d.tokens[d.cursor].File == d.tokens[d.cursor+1].File &&
		d.tokens[d.cursor].Line+d.numLineBreaks(d.cursor) == d.tokens[d.cursor+1].Line {
		d.cursor++
		return true
	}
	return false
}

// nextOnSameLine advances the cursor if the next token is on the same line of the same file.
func (d *Dispenser) nextOnSameLine() bool {
	if d.cursor < 0 {
		d.cursor++
		return true
	}
	if d.cursor >= len(d.tokens)-1 {
		return false
	}
	curr := d.tokens[d.cursor]
	next := d.tokens[d.cursor+1]
	if !isNextOnNewLine(curr, next) {
		d.cursor++
		return true
	}
	return false
}

// NextLine loads the next token only if it is not on the same line as the current token, and returns true if a token was
// loaded; false otherwise. If false, there is not another token or it is on the same line. It handles imported tokens correctly.
func (d *Dispenser) NextLine() bool {
	if d.cursor < 0 {
		d.cursor++
		return true
	}
	if d.cursor >= len(d.tokens) {
		return false
	}
	if d.cursor < len(d.tokens)-1 &&
		(d.tokens[d.cursor].File != d.tokens[d.cursor+1].File ||
			d.tokens[d.cursor].Line+d.numLineBreaks(d.cursor) < d.tokens[d.cursor+1].Line) {
		d.cursor++
		return true
	}
	return false
}

// NextBlock can be used as the condition of a for loop to load the next token as long as it opens a block or
// is already in a block. It returns true if a token was loaded, or false when the block's closing curly brace
// was loaded and thus the block ended. Nested blocks are not supported.
func (d *Dispenser) NextBlock(initialNestingLevel int) bool {
	if d.nesting > initialNestingLevel {
		if !d.Next() {
			return false // should be EOF error
		}
		if d.Val() == "}" && !d.nextOnSameLine() {
			d.nesting--
		} else if d.Val() == "{" && !d.nextOnSameLine() {
			d.nesting++
		}
		return d.nesting > initialNestingLevel
	}
	if !d.nextOnSameLine() { // block must open on same line
		return false
	}
	if d.Val() != "{" {
		d.cursor-- // roll back if not opening brace
		return false
	}
	if !d.Next() {
		return false
	}
	if d.Val() == "}" {
		// Open and then closed right away
		return false
	}
	d.nesting++
	return true
}

// Nesting returns the current nesting level. Necessary if using NextBlock()
func (d *Dispenser) Nesting() int {
	return d.nesting
}

// Val gets the text of the current token. If there is no token loaded, it returns empty string.
func (d *Dispenser) Val() string {
	if d.cursor < 0 || d.cursor >= len(d.tokens) {
		return ""
	}
	return d.tokens[d.cursor].Text
}

// Line gets the line number of the current token. If there is no token loaded, it returns 0.
func (d *Dispenser) Line() int {
	if d.cursor < 0 || d.cursor >= len(d.tokens) {
		return 0
	}
	return d.tokens[d.cursor].Line
}

// File gets the filename of the current token. If there is no token loaded,
// it returns the filename originally given when parsing started.
func (d *Dispenser) File() string {
	if d.cursor < 0 || d.cursor >= len(d.tokens) {
		return d.filename
	}
	if tokenFilename := d.tokens[d.cursor].File; tokenFilename != "" {
		return tokenFilename
	}
	return d.filename
}

// Keys returns the keys of the block we are parsing right now.
func (d *Dispenser) Keys() []string { return d.keys }

// Args is a convenience function that loads the next arguments (tokens on the same line) into an arbitrary number of strings
// pointed to in targets. If there are fewer tokens available than string pointers, the remaining strings will not be changed
// and false will be returned. If there were enough tokens available to fill the arguments, then true will be returned.
func (d *Dispenser) Args(targets ...*string) bool {
	enough := true
	for i := range len(targets) {
		if !d.NextArg() {
			enough = false
			break
		}
		*targets[i] = d.Val()
	}
	return enough
}

// RemainingArgs loads any more arguments (tokens on the same line) into a slice and returns them. Open curly brace tokens also indicate
// the end of arguments, and the curly brace is not included in the return value nor is it loaded.
func (d *Dispenser) RemainingArgs() []string {
	var args []string

	for d.NextArg() {
		if d.Val() == "{" {
			d.cursor--
			break
		}
		args = append(args, d.Val())
	}

	return args
}

// ArgErr returns an argument error, meaning that another argument was expected but not found. In other words,
// a line break or open curly brace was encountered instead of an argument.
func (d *Dispenser) ArgErr() error {
	if d.Val() == "{" {
		return d.Errf("unexpected token '{', expecting argument")
	}
	return d.Errf("wrong argument count or unexpected line ending after '%s'", d.Val())
}

// PropErr return a property error, meaning that x was expect but we got y.
func (d *Dispenser) PropErr(err ...error) error {
	if len(err) > 0 {
		return d.Errf("unexpected property: '%s': %s", d.Val(), err[0].Error())
	}
	return d.Errf("unexpected property: %s", d.Val())
}

// SyntaxErr creates a generic syntax error which explains what was found and what was expected.
func (d *Dispenser) SyntaxErr(expected string) error {
	msg := fmt.Sprintf("%s:%d - syntax error: unexpected token '%s', expecting '%s'", d.File(), d.Line(), d.Val(), expected)
	return errors.New(msg)
}

// PropEmptyErr create a error that a property was not defined or still empty after parsing.
func (d *Dispenser) PropEmptyErr(prop string) error {
	msg := fmt.Sprintf("property: '%s' can not be empty", prop)
	return errors.New(msg)
}

// EOFErr returns an error indicating that the dispenser reached the end of the input when searching for the next token.
func (d *Dispenser) EOFErr() error {
	return d.Errf("unexpected EOF")
}

// Err generates a custom parse-time error with a message of msg.
func (d *Dispenser) Err(err error) error {
	return fmt.Errorf("%s:%d - error parsing or initializing: %w", d.File(), d.Line(), err)
}

// Errf is like Err, but for formatted error messages
func (d *Dispenser) Errf(format string, args ...any) error { return d.Err(fmt.Errorf(format, args...)) }

// numLineBreaks counts how many line breaks are in the token value given by the token index tknIdx. It returns 0 if the
// token does not exist or there are no line breaks.
func (d *Dispenser) numLineBreaks(tknIdx int) int {
	if tknIdx < 0 || tknIdx >= len(d.tokens) {
		return 0
	}
	return strings.Count(d.tokens[tknIdx].Text, "\n")
}

// isNewLine determines whether the current token is on a different line (higher line number) than the
// previous token. It handles imported tokens correctly. If there isn't a previous token, it returns true.
func (d *Dispenser) isNewLine() bool {
	if d.cursor < 1 {
		return true
	}
	if d.cursor > len(d.tokens)-1 {
		return false
	}

	prev := d.tokens[d.cursor-1]
	curr := d.tokens[d.cursor]
	return isNextOnNewLine(prev, curr)
}

// Addr parses the host and port in the current token, i.e. 127.0.0.0:53 is parsed and returned, same for
// IPv6 addresses [2004:32]:53. If there is no port the default port will be added (53).
func (d *Dispenser) Addr() (string, error) { return addr(d.Val()) }

// RemainingAddrs calls RemainingArgs and return each actual address. If the address does not have
// port :53 is added.
func (d *Dispenser) RemainingAddrs() ([]string, error) {
	args := d.RemainingArgs()
	for i := range args {
		addr, err := addr(args[i])
		if err != nil {
			return nil, err
		}
		args[i] = addr
	}
	return args, nil
}

func addr(s string) (string, error) {
	addr, port, err := net.SplitHostPort(s)
	if err != nil {
		if net.ParseIP(s) == nil {
			return "", fmt.Errorf("failed to parse '%s' as IP", s)
		}
		return net.JoinHostPort(s, "53"), nil
	}
	return net.JoinHostPort(addr, port), nil
}

// RemainingIPs calls RemainingArgs and return all IPs. If a arg does not look like an IP, it is assume to be
// a interface name.
func (d *Dispenser) RemainingIPs() ([]string, error) {
	args := d.RemainingArgs()
	ips := []string{}
	for i := range args {
		x := net.ParseIP(args[i])
		if x != nil {
			ips = append(ips, args[i])
			continue
		}
		ifips := iface.List(args[i])
		if len(ifips) == 0 {
			return nil, fmt.Errorf("failed to find routable IPs on '%s' interface", args[i])
		}
		ips = append(ips, ifips...)
	}
	return ips, nil
}

// RemainingDurations calls RemainingArgs and returns all arguments as parsed time.Durations or an error.
func (d *Dispenser) RemainingDurations() ([]time.Duration, error) {
	args := d.RemainingArgs()
	durs := []time.Duration{}
	for i := range args {
		x, err := time.ParseDuration(args[i])
		if err != nil {
			return durs, err
		}
		durs = append(durs, x)
	}
	return durs, nil
}

// Tilde will replace "~" as the first path element with the home directory of the user running us.
func Tilde(s string) string {
	if !strings.HasPrefix(s, "~") {
		return s
	}
	home, err := os.UserHomeDir()
	if err != nil {
		return s
	}
	return filepath.Join(home, strings.TrimPrefix(s, "~"))
}
