/*
Copyright © 2021 da/net Research Group <danet@h-da.de>
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

3. Neither the name of the copyright holder nor the names of its contributors
   may be used to endorse or promote products derived from this software
   without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/

package cmd

import (
	"os"
	"strings"

	"code.fbi.h-da.de/danet/gosdn/cli/completer"
	"code.fbi.h-da.de/danet/gosdn/controller/api"
	"github.com/c-bata/go-prompt"
	"github.com/google/uuid"
	"github.com/openconfig/goyang/pkg/yang"
	"github.com/pterm/pterm"
	"github.com/pterm/pterm/putils"
	"github.com/spf13/cobra"
	"github.com/spf13/pflag"
	"github.com/spf13/viper"
)

var c *PromptCompleter

// PromptCompleter provides completion for a Network Element.
type PromptCompleter struct {
	YangSchemaCompleterMap map[uuid.UUID]*completer.YangSchemaCompleter
	currentSuggestions     []prompt.Suggest
	// nolint:unused
	document *prompt.Document
	history  []string
}

// NewPromptCompleter returns a new promptCompleter.
func NewPromptCompleter() *PromptCompleter {
	return &PromptCompleter{
		YangSchemaCompleterMap: make(map[uuid.UUID]*completer.YangSchemaCompleter),
	}
}

// Run starts the interactive completion.
func (pc *PromptCompleter) Run() {
	title, _ := pterm.DefaultBigText.WithLetters(
		putils.LettersFromString("go"),
		putils.LettersFromStringWithStyle("SDN", pterm.NewStyle(pterm.FgCyan)),
		putils.LettersFromString("c"),
	).Srender()
	description := pterm.DefaultBasicText.Sprint("Control your goSDN controller like you've never done it before!")
	pterm.DefaultCenter.Println(title)
	pterm.DefaultCenter.Println(description)

	p := prompt.New(
		executeFunc,
		pc.cstmCompleter,
		prompt.OptionTitle("gosdnc-prompt: interactive gosdn CLI"),
		prompt.OptionPrefix(">>> "),
		prompt.OptionPrefixTextColor(prompt.Cyan),
		prompt.OptionCompletionWordSeparator(completer.YangSchemaCompletionSeperator),
		prompt.OptionShowCompletionAtStart(),
		prompt.OptionCompletionOnDown(),
		prompt.OptionHistory(pc.history),
		prompt.OptionSuggestionBGColor(prompt.DarkGray),
		prompt.OptionSuggestionTextColor(prompt.LightGray),
		prompt.OptionDescriptionTextColor(prompt.DarkGray),
		prompt.OptionDescriptionBGColor(prompt.LightGray),
		prompt.OptionSelectedSuggestionBGColor(prompt.Cyan),
		prompt.OptionSelectedSuggestionTextColor(prompt.DarkGray),
		prompt.OptionSelectedDescriptionBGColor(prompt.LightGray),
		prompt.OptionSelectedDescriptionTextColor(prompt.DarkGray),
	)

	p.Run()
}

func executeFunc(s string) {
	if s := strings.TrimSpace(s); s == "" {
		return
	}
	rootCmd.SetArgs(strings.Fields(s))
	err := rootCmd.Execute()

	if err != nil {
		pterm.Error.Println("Could not execute:", err)
	}
}

func (pc *PromptCompleter) cstmCompleter(d prompt.Document) []prompt.Suggest {
	// Start with the cobra 'rootCmd' and walk through it
	// Reference: https://github.com/stromland/cobra-prompt
	currCmd := rootCmd
	inputSplit := strings.Fields(d.CurrentLine())
	inputSplitFiltered, inputFlags := filterFlagSlice(inputSplit)
	if c, _, err := currCmd.Find(inputSplitFiltered); err == nil {
		currCmd = c
	}

	return completionBasedOnCmd(pc, currCmd, inputSplit, inputSplitFiltered, inputFlags, d)
}

func filterFlagSlice(input []string) (commandSlice []string, flagSlice []string) {
	for _, in := range input {
		if !strings.HasPrefix(in, "--") {
			commandSlice = append(commandSlice, in)
		} else {
			flagSlice = append(flagSlice, strings.Split(in, "=")[0])
		}
	}
	return commandSlice, flagSlice
}

func networkElementGetCompletion(c *PromptCompleter, d prompt.Document, inputSplit []string) []prompt.Suggest {
	switch inputLen := len(inputSplit); inputLen {
	case 2:
		return c.updateSuggestionsThroughFunc(d, getNetworkElements)
	case 3:
		id, err := uuid.Parse(inputSplit[inputLen-1])
		if err != nil {
			return c.updateSuggestionsThroughFunc(d, getNetworkElements)
		}
		if c, ok := c.YangSchemaCompleterMap[id]; ok {
			return c.Complete(d)
		}
		schemaTree, err := getSchemaTreeForNetworkElementID(id)
		if err != nil {
			return []prompt.Suggest{}
		}
		c.YangSchemaCompleterMap[id] = completer.NewYangSchemaCompleter(schemaTree["Device"], true)
		if yc, ok := c.YangSchemaCompleterMap[id]; ok {
			return yc.Complete(d)
		}
	case 4:
		if d.GetWordBeforeCursor() == "" || d.GetWordAfterCursor() != "" {
			id, err := uuid.Parse(inputSplit[inputLen-2])
			if err != nil {
				return c.updateSuggestionsThroughFunc(d, getNetworkElements)
			}
			if yc, ok := c.YangSchemaCompleterMap[id]; ok {
				err := yc.UpdateEntry(inputSplit[inputLen-1])
				if err != nil {
					pterm.Error.Println(err)
				}
			}
			return []prompt.Suggest{}
		}
		id, err := uuid.Parse(inputSplit[inputLen-2])
		if err != nil {
			return c.updateSuggestionsThroughFunc(d, getNetworkElements)
		}
		if yc, ok := c.YangSchemaCompleterMap[id]; ok {
			return yc.Complete(d)
		}
	default:
		return []prompt.Suggest{}
	}
	return []prompt.Suggest{}
}

func (pc *PromptCompleter) updateSuggestionsThroughFunc(d prompt.Document, fn func() ([]prompt.Suggest, error)) []prompt.Suggest {
	if pc.currentSuggestions == nil {
		var err error
		pc.currentSuggestions, err = fn()
		if err != nil {
			return prompt.FilterHasPrefix(pc.currentSuggestions, d.GetWordBeforeCursor(), true)
		}
	}
	return prompt.FilterHasPrefix(pc.currentSuggestions, d.GetWordBeforeCursor(), true)
}

func cobraCommandCompletion(currCmd *cobra.Command, d prompt.Document, inputFlags []string, loaded []prompt.Suggest) []prompt.Suggest {
	if currCmd.HasAvailableFlags() {
		currCmd.LocalFlags().VisitAll(
			func(f *pflag.Flag) {
				if !f.Hidden && !sliceContains(inputFlags, "--"+f.Name) {
					loaded = append(loaded, prompt.Suggest{Text: "--" + f.Name, Description: f.Usage})
				}
			},
		)
	}

	for _, cmd := range currCmd.Commands() {
		loaded = append(loaded, prompt.Suggest{Text: cmd.Name(), Description: cmd.Short})
	}

	return prompt.FilterHasPrefix(loaded, d.GetWordBeforeCursor(), true)
}

// nolint
func completionBasedOnCmd(c *PromptCompleter, cmd *cobra.Command, inputSplit []string, inputSplitFiltered []string, inputFlags []string, d prompt.Document) []prompt.Suggest {
	switch cmd {
	case pndUseCmd, pndGetCmd, pndRemoveCmd:
		if len(inputSplitFiltered) < 3 || (len(inputSplitFiltered) == 3 && d.GetWordBeforeCursor() != "") {
			suggestions := c.updateSuggestionsThroughFunc(d, getPnds)
			return cobraCommandCompletion(cmd, d, inputFlags, suggestions)
		}
	case commitCmd:
		if len(inputSplitFiltered) < 3 || (len(inputSplitFiltered) == 3 && d.GetWordBeforeCursor() != "") {
			return c.updateSuggestionsThroughFunc(d, getPendingChanges)
		}
	case confirmCmd:
		if len(inputSplitFiltered) < 3 || (len(inputSplitFiltered) == 3 && d.GetWordBeforeCursor() != "") {
			return c.updateSuggestionsThroughFunc(d, getCommittedChanges)
		}
	case networkElementRemoveCmd:
		if len(inputSplitFiltered) < 3 || (len(inputSplitFiltered) == 3 && d.GetWordBeforeCursor() != "") {
			return c.updateSuggestionsThroughFunc(d, getNetworkElements)
		}
	case networkElementCreateCmd:
		if len(inputFlags) != 0 {
			if inputFlags[len(inputFlags)-1] == "--plugin-id" &&
				((inputSplit[len(inputSplit)-1] == "--plugin-id" && d.GetWordBeforeCursor() == "") ||
					(inputSplit[len(inputSplit)-2] == "--plugin-id" && d.GetWordBeforeCursor() != "")) {
				return c.updateSuggestionsThroughFunc(d, getAvailablePlugins)
			} else {
				return cobraCommandCompletion(cmd, d, inputFlags, []prompt.Suggest{})
			}
		} else {
			return cobraCommandCompletion(cmd, d, inputFlags, []prompt.Suggest{})
		}
	case networkElementGetPathCmd, networkElementGetIntendedPathCmd, networkElementSetCmd:
		return networkElementGetCompletion(c, d, inputSplitFiltered)
	case networkElementShowCmd:
		networkElements, err := getNetworkElements()
		if err != nil {
			return []prompt.Suggest{}
		}
		return networkElements
	case networkElementCmd, pndCmd, changeCmd:
		c.currentSuggestions = nil
		return cobraCommandCompletion(cmd, d, inputFlags, []prompt.Suggest{})
	default:
		return cobraCommandCompletion(cmd, d, inputFlags, []prompt.Suggest{})
	}

	return []prompt.Suggest{}
}

// getNetworkElements is a helper function which requests Network Elements from the controller
// and gives feedback about the current pulling status with the help of pterm
// the result is converted into a prompt.Suggest slice.
func getNetworkElements() ([]prompt.Suggest, error) {
	spinner, _ := pterm.DefaultSpinner.Start("Fetching Network Elements from controller.")
	resp, err := pndAdapter.GetFlattenedNetworkElements(createContextWithAuthorization())
	if err != nil {
		spinner.Fail(err)
		return []prompt.Suggest{}, err
	}

	s := []prompt.Suggest{}
	for _, mne := range resp.Mne {
		s = append(s, prompt.Suggest{Text: mne.GetId(), Description: mne.GetName()})
	}
	spinner.Success()
	return completer.SortSuggestionByText(s), nil
}

func getAvailablePlugins() ([]prompt.Suggest, error) {
	spinner, _ := pterm.DefaultSpinner.Start("Fetching available plugins from controller.")
	resp, err := pndAdapter.GetAvailablePlugins(createContextWithAuthorization())
	if err != nil {
		spinner.Fail(err)
		return []prompt.Suggest{}, err
	}

	s := []prompt.Suggest{}
	for _, plugin := range resp.GetPlugins() {
		s = append(s, prompt.Suggest{Text: plugin.GetId(), Description: plugin.Manifest.GetName()})
	}
	spinner.Success()
	return completer.SortSuggestionByText(s), nil
}

// getSchemaTreeForNetworkElementID is a helper function which requests the SBI's
// schema tree of a specific Network Element. The function gives feedback about the
// current pulling status with the help of pterm.
func getSchemaTreeForNetworkElementID(id uuid.UUID) (map[string]*yang.Entry, error) {
	spinner, _ := pterm.DefaultSpinner.Start("Fetching schema tree for Device with ID: ", id)

	networkElement, err := pndAdapter.GetFlattenedNetworkElement(createContextWithAuthorization(), id.String())
	if err != nil {
		spinner.Fail(err)
		return nil, err
	}

	pluginID := networkElement.GetMne().GetPluginid()
	pluginUUID := uuid.MustParse(pluginID)
	schemaTree, err := pndAdapter.GetPluginSchemaTree(createContextWithAuthorization(), pluginUUID)
	if err != nil {
		spinner.Fail(err)
		return nil, err
	}
	spinner.Success()
	return schemaTree, nil
}

// getPnds is a helper function which requests pnds from the controller and
// gives feedback about the current pulling status with the help of pterm the
// result is converted into a prompt.Suggest slice.
func getPnds() ([]prompt.Suggest, error) {
	spinner, _ := pterm.DefaultSpinner.Start("Fetching PNDs from controller.")
	resp, err := api.GetIds(createContextWithAuthorization(), viper.GetString("controllerAPIEndpoint"))
	if err != nil {
		spinner.Fail(err)
		return []prompt.Suggest{}, err
	}

	s := []prompt.Suggest{}
	for _, pnd := range resp {
		s = append(s, prompt.Suggest{Text: pnd.GetId(), Description: pnd.GetDescription()})
	}
	spinner.Success()
	return completer.SortSuggestionByText(s), nil
}

// getPendingChanges is a helper function which requests all the pending
// changes from the controller and gives feedback about the current pulling
// status with the help of pterm the result is converted into a prompt.Suggest
// slice.
func getPendingChanges() ([]prompt.Suggest, error) {
	spinner, _ := pterm.DefaultSpinner.Start("Fetching committed changes.")

	resp, err := pndAdapter.PendingChanges(createContextWithAuthorization())
	if err != nil {
		spinner.Fail(err)
		return []prompt.Suggest{}, err
	}

	s := []prompt.Suggest{}
	for _, change := range resp {
		s = append(s, prompt.Suggest{Text: change.GetId(), Description: change.State.String()})
	}
	spinner.Success()
	return completer.SortSuggestionByText(s), nil
}

// getCommittedChanges is a helper function which requests all the committed
// changes from the controller and gives feedback about the current pulling
// status with the help of pterm the result is converted into a prompt.Suggest
// slice.
func getCommittedChanges() ([]prompt.Suggest, error) {
	spinner, _ := pterm.DefaultSpinner.Start("Fetching pending changes.")

	resp, err := pndAdapter.CommittedChanges(createContextWithAuthorization())
	if err != nil {
		spinner.Fail(err)
		return []prompt.Suggest{}, err
	}

	s := []prompt.Suggest{}
	for _, change := range resp {
		s = append(s, prompt.Suggest{Text: change.GetId(), Description: change.State.String()})
	}
	spinner.Success()
	return completer.SortSuggestionByText(s), nil
}

var exitCmd = &cobra.Command{
	Use:   "exit",
	Short: "The exit command exits the interactive prompt mode.",
	Long:  `The exit command exits the interactive prompt mode.`,

	RunE: func(cmd *cobra.Command, args []string) error {
		os.Exit(0)

		return nil
	},
}

var promptCmd = &cobra.Command{
	Use:   "prompt",
	Short: "The prompt command runs the CLI in an interactive shell.",
	Long: `The prompt command rund the CLI in an interactive shell and
    provides the user with autocompletion and more...`,

	RunE: func(cmd *cobra.Command, args []string) error {
		c = NewPromptCompleter()
		c.Run()

		return nil
	},
}

func init() {
	rootCmd.AddCommand(promptCmd)
	rootCmd.AddCommand(exitCmd)
}
