// exportable typescript generated from golang
// Copyright (C) 2022  Fabio Prada

package tsrpc

import (
	"bytes"

	"fmt"
	"os"
	"text/template"
	"time"
)

// configuration

type TSConfig struct {
	Url   string
	TsApi *string
	Path  string
}

type tsTemplateData struct {
	APIURL    string
	CreatedOn time.Time
}

var tsConfig TSConfig

func GetTSSource(config TSConfig) string {
	tsConfig = config
	var tsInfoData = TSInfo{}
	var tsSourcesData = TSSouces{}
	tsInfoData.Populate(tsConfig.Path)
	tsInfoData.TestEndpoints()
	tsSourcesData.Populate(tsInfoData)

	if len(tsSourcesData.Errors) != 0 {
		err := ""
		for _, v := range tsSourcesData.Errors {
			err += fmt.Sprintln(v)
		}
		exitOnError(fmt.Errorf("some errors...\n %s", err))
	}

	tsSource := ""
	data := ""
	if tsConfig.TsApi == nil {
		data = TsApiTemplate
	} else {
		d, err := os.ReadFile(*tsConfig.TsApi)
		if err != nil {
			panic(err)
		}
		data = string(d)
	}

	t, err := template.New("tsRpc").Parse(data)
	if err != nil {
		panic(err)
	}
	var templateData = tsTemplateData{
		APIURL:    config.Url,
		CreatedOn: time.Now(),
	}
	var result bytes.Buffer
	err = t.Execute(&result, templateData)
	if err != nil {
		panic(err)
	}
	tsSource += result.String()

	tsSource += fmt.Sprintln("\n// Global Declarations ")
	for p := range tsSourcesData.Pakages {
		for _, v1 := range tsSourcesData.Pakages[p].GTypes {
			tsSource += fmt.Sprintln(v1)
		}
	}

	for p := range tsSourcesData.Pakages {
		source := ""
		head := fmt.Sprintf("\n//\n// package %s\n//\n", p)
		for _, v1 := range tsSourcesData.Pakages[p].Endpoints {
			source += fmt.Sprintln(v1)
		}
		for _, v1 := range tsSourcesData.Pakages[p].Structs {
			source += fmt.Sprintln(v1)
		}
		for _, v1 := range tsSourcesData.Pakages[p].Types {
			source += fmt.Sprintln(v1)
		}
		for _, v1 := range tsSourcesData.Pakages[p].Enums {
			source += fmt.Sprintln(v1)
		}
		for _, v1 := range tsSourcesData.Pakages[p].Consts {
			source += fmt.Sprintln(v1)
		}

		if len(source) > 0 {
			tsSource += head + source + "\n\n"
		}
	}
	return tsSource
}
