// Copyright © 2022 The Tekton 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 export

import (
	"fmt"
	"regexp"

	"github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"sigs.k8s.io/yaml"
)

// pipelineExportRemoveExtraFields some of the fields are not getting skipped, when set as nil,
// like creationTimeStamp since it's a time.Time that is not a pointer yaml would display a creationTimeStamp: null
// let's do some regexp magic here, which should hopefully safe.
func pipelineExportRemoveExtraFields(input string) string {
	m1 := regexp.MustCompile(`\n  creationTimestamp: null\n`)
	return m1.ReplaceAllString(input, "\n")
}

// TektonResourceToYaml convert a pipeline to yaml removing extraneous fields generated by k8/tekton controllers so we can
// easily reimport theme
func TektonResourceToYaml(p interface{}) (string, error) {
	// I gave up trying to do a generic function....
	// if someone have a better idea please let me know
	switch o := p.(type) {
	case *v1beta1.PipelineRun:
		o.ObjectMeta.ManagedFields = nil
		o.ObjectMeta.ResourceVersion = ""
		o.ObjectMeta.UID = ""
		o.ObjectMeta.Generation = 0
		o.ObjectMeta.Namespace = ""
		o.ObjectMeta.CreationTimestamp = metav1.Time{}
		o.Status = v1beta1.PipelineRunStatus{}

		if o.ObjectMeta.GenerateName != "" {
			o.ObjectMeta.Name = ""
		}

		data, err := yaml.Marshal(o)
		return pipelineExportRemoveExtraFields(string(data)), err
	case *v1beta1.Pipeline:
		o.ObjectMeta.ManagedFields = nil
		o.ObjectMeta.ResourceVersion = ""
		o.ObjectMeta.UID = ""
		o.ObjectMeta.Generation = 0
		o.ObjectMeta.Namespace = ""
		o.ObjectMeta.CreationTimestamp = metav1.Time{}

		if o.ObjectMeta.GenerateName != "" {
			o.ObjectMeta.Name = ""
		}

		data, err := yaml.Marshal(o)
		return pipelineExportRemoveExtraFields(string(data)), err
	}
	return "", fmt.Errorf("cannot convert %+v", p)
}
