/*
Copyright 2019 The Kubernetes Authors.

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 deepcopy

import (
	"bytes"
	"fmt"
	"go/ast"
	"go/format"
	"io"
	"sort"
	"strings"

	"sigs.k8s.io/controller-tools/pkg/genall"
	"sigs.k8s.io/controller-tools/pkg/loader"
	"sigs.k8s.io/controller-tools/pkg/markers"
)

// NB(directxman12): markers.LoadRoots ignores autogenerated code via a build tag
// so any time we check for existing deepcopy functions, we only seen manually written ones.

const (
	objName    = "kubebuilder:object:root"
	enableName = "kubebuilder:object:generate"

	legacyEnableName = "k8s:deepcopy-gen"
	legacyObjName    = "k8s:deepcopy-gen:interfaces"
	runtimeObjPath   = "k8s.io/apimachinery/pkg/runtime.Object"
)

// Generator generates code code containing DeepCopy, DeepCopyInto, and
// DeepCopyObject method implementations.
type Generator struct {
	HeaderFile string `marker:",optional"`
	Year       string `marker:",optional"`
}

func (Generator) RegisterMarkers(into *markers.Registry) error {
	if err := into.Define(enableName, markers.DescribesPackage, false); err != nil {
		return err
	}
	if err := into.Define(legacyEnableName, markers.DescribesPackage, markers.RawArguments(nil)); err != nil {
		return err
	}
	if err := into.Define(enableName, markers.DescribesType, false); err != nil {
		return err
	}
	if err := into.Define(legacyEnableName, markers.DescribesType, markers.RawArguments(nil)); err != nil {
		return err
	}
	if err := into.Define(objName, markers.DescribesType, false); err != nil {
		return err
	}
	if err := into.Define(legacyObjName, markers.DescribesType, ""); err != nil {
		return err
	}
	return nil
}

func enabledOnPackage(col *markers.Collector, pkg *loader.Package) (bool, error) {
	pkgMarkers, err := markers.PackageMarkers(col, pkg)
	if err != nil {
		return false, err
	}
	pkgMarker := pkgMarkers.Get(enableName)
	if pkgMarker != nil {
		return pkgMarker.(bool), nil
	}
	legacyMarker := pkgMarkers.Get(legacyEnableName)
	if legacyMarker != nil {
		legacyMarkerVal := string(legacyMarker.(markers.RawArguments))
		firstArg := strings.Split(legacyMarkerVal, ",")[0]
		return firstArg == "package", nil
	}

	return false, nil
}

func enabledOnType(allTypes bool, info *markers.TypeInfo) bool {
	if typeMarker := info.Markers.Get(enableName); typeMarker != nil {
		return typeMarker.(bool)
	}
	legacyMarker := info.Markers.Get(legacyEnableName)
	if legacyMarker != nil {
		legacyMarkerVal := string(legacyMarker.(markers.RawArguments))
		return legacyMarkerVal == "true"
	}
	return allTypes || genObjectInterface(info)
}

func genObjectInterface(info *markers.TypeInfo) bool {
	objectEnabled := info.Markers.Get(objName)
	if objectEnabled != nil {
		return objectEnabled.(bool)
	}

	for _, legacyEnabled := range info.Markers[legacyObjName] {
		if legacyEnabled == runtimeObjPath {
			return true
		}
	}
	return false
}

func (d Generator) Generate(ctx *genall.GenerationContext) error {
	var headerText string

	checker := ctx.Checker

	if d.HeaderFile != "" {
		headerBytes, err := ctx.ReadFile(d.HeaderFile)
		if err != nil {
			return err
		}
		headerText = string(headerBytes)
	}
	headerText = strings.ReplaceAll(headerText, " YEAR", d.Year)

	for _, root := range ctx.Roots {
		allTypes, err := enabledOnPackage(ctx.Collector, root)
		if err != nil {
			root.AddError(err)
			continue
		}

		checker.Check(root, func(node ast.Node) bool {
			// ignore interfaces
			_, isIface := node.(*ast.InterfaceType)
			return !isIface
		})

		root.NeedTypesInfo()

		byType := make(map[string][]byte)
		imports := &importsList{
			byPath:  make(map[string]string),
			byAlias: make(map[string]string),
			pkg:     root,
		}
		// avoid confusing aliases by "reserving" the root package's name as an alias
		imports.byAlias[root.Name] = ""

		if err := markers.EachType(ctx.Collector, root, func(info *markers.TypeInfo) {
			outContent := new(bytes.Buffer)

			// copy when nabled for all types and not disabled, or enabled
			// specifically on this type
			if !enabledOnType(allTypes, info) {
				return
			}

			// avoid copying non-exported types, etc
			if !shouldBeCopied(root, info) {
				return
			}

			copyCtx := &copyMethodMaker{
				pkg:         root,
				importsList: imports,
				codeWriter:  &codeWriter{out: outContent},
			}

			copyCtx.GenerateMethodsFor(root, info)

			outBytes := outContent.Bytes()
			if len(outBytes) > 0 {
				byType[info.Name] = outBytes
			}
		}); err != nil {
			root.AddError(err)
			continue
		}

		if len(byType) == 0 {
			continue
		}

		outContent := new(bytes.Buffer)
		writeHeader(root, outContent, root.Name, imports, headerText)
		writeMethods(root, outContent, byType)

		writeFormatted(ctx, root, outContent.Bytes())
	}

	return nil
}

// writeHeader writes out the build tag, package declaration, and imports
func writeHeader(pkg *loader.Package, out io.Writer, packageName string, imports *importsList, headerText string) {
	// NB(directxman12): blank line after build tags to distinguish them from comments
	_, err := fmt.Fprintf(out, `// +build !ignore_autogenerated

%[3]s

// autogenerated by controller-gen object, do not modify manually

package %[1]s

import (
%[2]s
)

`, packageName, strings.Join(imports.ImportSpecs(), "\n"), headerText)
	if err != nil {
		pkg.AddError(err)
	}

}

// writeMethods writes each method to the file, sorted by type name.
func writeMethods(pkg *loader.Package, out io.Writer, byType map[string][]byte) {
	sortedNames := make([]string, 0, len(byType))
	for name := range byType {
		sortedNames = append(sortedNames, name)
	}
	sort.Strings(sortedNames)

	for _, name := range sortedNames {
		_, err := out.Write(byType[name])
		if err != nil {
			pkg.AddError(err)
		}
	}
}

// writeFormatted outputs the given code, after gofmt-ing it.  If we couldn't gofmt,
// we write the unformatted code for debugging purposes.
func writeFormatted(ctx *genall.GenerationContext, root *loader.Package, outBytes []byte) {
	formattedBytes, err := format.Source(outBytes)
	if err != nil {
		root.AddError(err)
		// we still write the invalid source to disk to figure out what went wrong
	} else {
		outBytes = formattedBytes
	}

	outputFile, err := ctx.Open(root, "zz_generated.deepcopy.go")
	if err != nil {
		root.AddError(err)
		return
	}
	defer outputFile.Close()
	n, err := outputFile.Write(outBytes)
	if err != nil {
		root.AddError(err)
		return
	}
	if n < len(outBytes) {
		root.AddError(io.ErrShortWrite)
	}
}
