// Copyright (c) 2022 Alibaba Group Holding Ltd.
//
// 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 config

import (
	"encoding/json"
	"fmt"
	"os"
	"strings"
	"text/template"

	"github.com/alibaba/higress/hgctl/pkg/plugin/types"
	"github.com/alibaba/higress/hgctl/pkg/plugin/utils"

	"gopkg.in/yaml.v3"
)

// TODO(WeixinX): Use 'hgctl plugin push' command to fill the image url automatically
const pluginConfYAML = `# File generated by hgctl. Modify as required.
# See: https://higress.io/zh-cn/docs/plugins/intro

apiVersion: extensions.higress.io/v1alpha1
kind: WasmPlugin
metadata:
  name: {{ .Name }}
  namespace: {{ .Namespace }}
  annotations:
    higress.io/wasm-plugin-title: {{ .Title }}
    higress.io/wasm-plugin-description: {{ .Description }}
    higress.io/wasm-plugin-icon: {{ .IconUrl }}
  labels:
    higress.io/wasm-plugin-name: {{ .Name }}
    higress.io/wasm-plugin-category: {{ .Category }}
    higress.io/wasm-plugin-version: {{ .Version }}
    higress.io/resource-definer: higress
    higress.io/wasm-plugin-built-in: "false"
spec:
  phase: {{ .Phase }}
  priority: {{ .Priority }}
{{ .Config }}
  # Please fill the image url in according to your needs
  url: {{ .Url }}
`

type PluginConf struct {
	Name        string
	Namespace   string
	Title       string
	Description string
	IconUrl     string
	Version     string
	Category    string
	Phase       string
	Priority    int64
	Config      string
	Url         string
}

func (pc *PluginConf) String() string {
	b, err := json.MarshalIndent(pc, "", "  ")
	if err != nil {
		return ""
	}
	return string(b)
}

// GenPluginConfYAML generates plugin-conf.yaml based on the template
func GenPluginConfYAML(p *PluginConf, dir string) error {
	path := fmt.Sprintf("%s/plugin-conf.yaml", dir)
	f, err := os.Create(path)
	if err != nil {
		return err
	}
	defer f.Close()

	if err = template.Must(template.New("PluginConfYAML").Parse(pluginConfYAML)).Execute(f, p); err != nil {
		return err
	}

	return nil
}

// ExtractPluginConfFrom extracts the params of plugin-conf.yaml from spec.yaml.
// input params `config`, `url` are only used to implement the command `hgctl plugin install -g <go-project>`
func ExtractPluginConfFrom(spec *types.WasmPluginMeta, config, url string) (*PluginConf, error) {
	if config == "" {
		// by default, Example from spec.yaml is used as the defaultConfig for the wasm plugin
		var obj map[string]interface{}
		example := spec.GetConfigExample()
		if err := yaml.Unmarshal([]byte(example), &obj); err != nil {
			return nil, err
		}
		conf := struct {
			DefaultConfig map[string]interface{} `yaml:"defaultConfig,omitempty"`
		}{DefaultConfig: obj}
		b, err := utils.MarshalYamlWithIndent(conf, 2)
		if err != nil {
			return nil, err
		}

		config = string(b)
	}

	pc := &PluginConf{
		Name:        spec.Info.Name,
		Namespace:   "higress-system",
		Title:       spec.Info.Title,
		Description: spec.Info.Description,
		IconUrl:     spec.Info.IconUrl,
		Version:     spec.Info.Version,
		Category:    string(spec.Info.Category),
		Phase:       string(spec.Spec.Phase),
		Priority:    spec.Spec.Priority,
		Config:      utils.AddIndent(config, strings.Repeat(" ", 2)),
		Url:         url,
	}
	pc.withDefaultValue()

	return pc, nil
}

func (pc *PluginConf) withDefaultValue() {
	if pc.Name == "" {
		pc.Name = "Unnamed"
	}
	if pc.Namespace == "" {
		pc.Namespace = "higress-system"
	}
	if pc.Title == "" {
		pc.Title = "Untitled"
	}
	if pc.Description == "" {
		pc.Description = "No description"
	}
	if pc.IconUrl == "" {
		pc.IconUrl = types.Category2IconUrl(types.Category(pc.Category))
	}
	if pc.Version == "" {
		pc.Version = "0.1.0"
	}
	if pc.Category == "" {
		pc.Category = string(types.CategoryDefault)
	}
	if pc.Phase == "" {
		pc.Phase = string(types.PhaseDefault)
	}
}
