/*
Copyright 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 util

import (
	"bytes"
	"encoding/json"
	"fmt"
	"os"

	"k8s.io/kube-openapi/pkg/common"
	"k8s.io/kube-openapi/pkg/validation/spec"
)

// OutputSchemas writes OpenAPI v2 schema JSON to stdout for the provided definitions.
func OutputSchemas(getDefinitions common.GetOpenAPIDefinitions) error {
	refFunc := func(name string) spec.Ref {
		return spec.MustCreateRef(fmt.Sprintf("#/definitions/%s", name))
	}

	defs := getDefinitions(refFunc)
	schemaDefs := make(map[string]spec.Schema, len(defs))

	for k, v := range defs {
		// Replace top-level schema with v2 if a v2 schema is embedded
		// so that the output of this program is always in OpenAPI v2.
		// This is done by looking up an extension that marks the embedded v2
		// schema, and, if the v2 schema is found, make it the resulting schema for
		// the type.
		if schema, ok := v.Schema.Extensions[common.ExtensionV2Schema]; ok {
			if v2Schema, isOpenAPISchema := schema.(spec.Schema); isOpenAPISchema {
				schemaDefs[k] = v2Schema
				continue
			}
		}
		schemaDefs[k] = v.Schema
	}

	// Use a buffer and encoder to control JSON formatting
	var buf bytes.Buffer
	encoder := json.NewEncoder(&buf)
	encoder.SetEscapeHTML(false) // Don't escape HTML characters like & < >
	encoder.SetIndent("", "  ")  // Pretty print with 2-space indent

	swagger := &spec.Swagger{
		SwaggerProps: spec.SwaggerProps{
			Definitions: schemaDefs,
			Info: &spec.Info{
				InfoProps: spec.InfoProps{
					Title:   "OpenShift API",
					Version: "unversioned",
				},
			},
			Swagger: "2.0",
		},
	}

	if err := encoder.Encode(swagger); err != nil {
		return fmt.Errorf("error serializing api definitions: %v\n", err)
	}

	if _, err := os.Stdout.Write(buf.Bytes()); err != nil {
		return fmt.Errorf("error writing api definitions: %v\n", err)
	}

	return nil
}
