// Copyright 2019 The Hugo Authors. All rights reserved.
//
// 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 page_generate

import (
	"errors"
	"fmt"
	"os"
	"path/filepath"
	"reflect"

	"github.com/gohugoio/hugo/codegen"
	"github.com/gohugoio/hugo/resources/page"
)

const header = `// Copyright 2019 The Hugo Authors. All rights reserved.
//
// 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.

// This file is autogenerated.
`

var (
	pageInterface = reflect.TypeOf((*page.PageMetaProvider)(nil)).Elem()

	packageDir = filepath.FromSlash("resources/page")
)

func Generate(c *codegen.Inspector) error {
	if err := generateMarshalJSON(c); err != nil {
		return fmt.Errorf("failed to generate JSON marshaler: %w", err)
	}

	return nil
}

func generateMarshalJSON(c *codegen.Inspector) error {
	filename := filepath.Join(c.ProjectRootDir, packageDir, "page_marshaljson.autogen.go")
	f, err := os.Create(filename)
	if err != nil {
		return err
	}
	defer f.Close()

	includes := []reflect.Type{pageInterface}

	excludes := []reflect.Type{}

	methods := c.MethodsFromTypes(
		includes,
		excludes)

	if len(methods) == 0 {
		return errors.New("no methods found")
	}

	marshalJSON, pkgImports := methods.ToMarshalJSON(
		"Page",
		"github.com/gohugoio/hugo/resources/page",
		// Exclusion regexps. Matches method names.
		`\bPage\b`,
	)

	fmt.Fprintf(f, `%s

package page

%s


%s


`, header, importsString(pkgImports), marshalJSON)

	return nil
}

func importsString(imps []string) string {
	if len(imps) == 0 {
		return ""
	}

	if len(imps) == 1 {
		return fmt.Sprintf("import %q", imps[0])
	}

	impsStr := "import (\n"
	for _, imp := range imps {
		impsStr += fmt.Sprintf("%q\n", imp)
	}

	return impsStr + ")"
}
