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

package tsrpc

import (
	"strings"

	"fmt"
	"os"
)

// configuration

var TSReport = ""

var tsFiles = TSFiles{}

func GetTSSource() error {
	path := ""
	if value, exists := os.LookupEnv("TS_GENERATOR_PATH"); exists {
		path = value
	} else {
		return fmt.Errorf("TS Generator PATH environment variable not set")
	}

	var tsInfoData = TSInfo{}
	var tsSourcesData = TSSouces{}
	tsInfoData.Populate(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))
	}

	// api file
	tsApi, err := GetApiFile()
	if err != nil {
		exitOnError(fmt.Errorf("some errors...\n %s", err))
	}
	tsFiles.Add("api.ts", tsApi)

	// index file
	tsApiDeclarations := []string{}
	tsIndexSource := ""
	tsIndexSource += fmt.Sprintln("\n// API Declarations ")
	for p := range tsSourcesData.Pakages {
		for _, v1 := range tsSourcesData.Pakages[p].GTypes {
			tsIndexSource += fmt.Sprintln(v1)
		}
		for _, v1 := range tsInfoData.Packages[p].decs {
			tsApiDeclarations = append(tsApiDeclarations, v1.Name[:strings.Index(v1.Name, "<")])
		}
	}

	tsFiles.Add("apiTypes.ts", tsIndexSource)

	for p := range tsSourcesData.Pakages {
		if p == "users" {
			fmt.Println("users package")
		}
		source := ""
		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 {
			tmp := ""

			found := false
			for _, sentence := range strings.Split(source, "\n") {
				if strings.Contains(sentence, "api.") {
					found = true
				}
			}
			if found {
				tmp += "import { api } from './api.ts'\n"
			}

			if len(tsApiDeclarations) > 0 {
				decs := []string{}

				for _, d := range tsApiDeclarations {
					found := false
					for _, sentence := range strings.Split(source, "\n") {
						if strings.Contains(sentence, d) {
							found = true
						}
					}
					if found {
						decs = append(decs, d)
					}
				}
				if len(decs) > 0 {
					TSApiDeclarations := "import { "
					for _, d := range decs {
						TSApiDeclarations += d + ", "
					}
					TSApiDeclarations = TSApiDeclarations[:len(TSApiDeclarations)-2]
					TSApiDeclarations += " } from './apiTypes.ts'\n"
					fmt.Println("tsApiDeclarations", TSApiDeclarations)
					tmp += TSApiDeclarations
				}
			}

			imports := ""
			for f := range tsSourcesData.Pakages[p].Imports {
				imports += "import * as " + f + " from './" + f + ".ts'\n"
			}
			tmp += imports
			tmp += source
			tsFiles.Add(p+".ts", tmp)
		}
	}

	err = tsFiles.Save()
	if err != nil {
		fmt.Printf("save ts files: %s\n", err)

	}
	return err
}
