// Copyright 2019 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0

package resource

import (
	"path/filepath"
	"strings"

	"sigs.k8s.io/kustomize/api/internal/git"
	kyaml "sigs.k8s.io/kustomize/kyaml/yaml"
)

// Origin retains information about the origin of resources and transformer configs
// that contributed to the output of `kustomize build`
type Origin struct {
	// Path is the path to the resource. If a local resource, this path is
	// rooted from the directory upon which `kustomize build` was invoked. If a
	// remote resource, this path is rooted from the root of the remote repo.
	Path string `json:"path,omitempty" yaml:"path,omitempty"`

	// Repo is the remote repository that the resource or transformer originated from if it is
	// not from a local file
	Repo string `json:"repo,omitempty" yaml:"repo,omitempty"`

	// Ref is the ref of the remote repository that the resource or transformer originated from
	// if it is not from a local file
	Ref string `json:"ref,omitempty" yaml:"ref,omitempty"`

	// The following fields only apply to resources that have been
	// generated by fields other than the `resources` field, or to transformer
	// configs.

	// ConfiguredIn is the file path to the generator or transformer config that created the
	// resource
	ConfiguredIn string `json:"configuredIn,omitempty" yaml:"configuredIn,omitempty"`

	// ConfiguredBy is the ObjectReference of the generator or transformer config
	ConfiguredBy kyaml.ResourceIdentifier `json:"configuredBy,omitempty" yaml:"configuredBy,omitempty"`
}

// Copy returns a copy of origin
func (origin *Origin) Copy() Origin {
	if origin == nil {
		return Origin{}
	}
	return *origin
}

// Append returns a copy of origin with a path appended to it
func (origin *Origin) Append(path string) *Origin {
	originCopy := origin.Copy()
	repoSpec, err := git.NewRepoSpecFromUrl(path)
	if err == nil {
		originCopy.Repo = repoSpec.Host + repoSpec.OrgRepo
		absPath := repoSpec.AbsPath()
		path = absPath[strings.Index(absPath[1:], "/")+1:][1:]
		originCopy.Path = ""
		originCopy.Ref = repoSpec.Ref
	}
	originCopy.Path = filepath.Join(originCopy.Path, path)
	return &originCopy
}

// String returns a string version of origin
func (origin *Origin) String() (string, error) {
	anno, err := kyaml.Marshal(origin)
	return string(anno), err
}

// Transformations is a list of Origin
type Transformations []*Origin

// String returns a string version of Transformations
func (transformations *Transformations) String() (string, error) {
	anno, err := kyaml.Marshal(transformations)
	return string(anno), err
}

// OriginFromCustomPlugin takes a custom plugin defined as a resource
// and returns an origin object to describe it
func OriginFromCustomPlugin(res *Resource) (*Origin, error) {
	origin, err := res.GetOrigin()
	if err != nil {
		return nil, err
	}
	var result *Origin
	if origin != nil {
		result = &Origin{
			Repo:         origin.Repo,
			Ref:          origin.Ref,
			ConfiguredIn: origin.Path,
			ConfiguredBy: kyaml.ResourceIdentifier{
				TypeMeta: kyaml.TypeMeta{
					APIVersion: res.GetApiVersion(),
					Kind:       res.GetKind(),
				},
				NameMeta: kyaml.NameMeta{
					Name:      res.GetName(),
					Namespace: res.GetNamespace(),
				},
			},
		}
	}
	return result, nil
}
