package main

import (
	"encoding/xml"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"reflect"
	"strings"
)

func MakeUppercase(s string) string {
	if s != "" && reflect.TypeOf(s).Kind() == reflect.String && len(s) > 0 {
		return strings.ToUpper(string(s[0])) + s[1:]
	}
	return ""
}

func CheckStringIfPresent(value *string) string {
	if value != nil {
		return strings.TrimSpace(*value)
	}
	return ""
}

func CheckStringIfPresentBool(value string) bool {
	if value != "" {
		return true
	} else {
		return false
	}
}

func fetchXML(url string) ([]byte, error) {
	resp, err := http.Get(url)
	if err != nil {
		return []byte{}, fmt.Errorf("GET error: %v", err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return []byte{}, fmt.Errorf("status error: %v", resp.StatusCode)
	}

	data, err := io.ReadAll(resp.Body)
	if err != nil {
		return []byte{}, fmt.Errorf("read body: %v", err)
	}

	return data, nil
}

func GetDataXML[T any](url string) T {
	xmlBytes, err := fetchXML(url)
	if err != nil {
		log.Fatalf("Failed to get XML: %v", err)
		panic(err)
	}
	var result T
	err = xml.Unmarshal(xmlBytes, &result)
	if err != nil {
		log.Fatalf("Failed to unmarshal XML: %v", err)
		panic(err)
	}
	return result
}

func GetPathsArray(path string) ([]string, error) {
	var paths []string

	err := filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		if !info.IsDir() {
			paths = append(paths, path)
		}
		return nil
	})

	if err != nil {
		return nil, err
	}

	return paths, nil
}

func GetPathDirsArray(path string) []string {
	var folderNames []string
	files, err := os.ReadDir(path)
	if err != nil {
		log.Fatal(err)
	}

	for _, file := range files {
		if file.IsDir() {
			folderNames = append(folderNames, file.Name())
		}
	}
	return folderNames
}

func GetStringValue(strPtr *string) string {
	if strPtr != nil {
		return *strPtr
	}
	return ""
}
func RemoveWhitespace(str string) string {
	return strings.ReplaceAll(str, " ", "")
}

func CommaToDot(str *string) *string {
	if str != nil {
		result := strings.ReplaceAll(*str, ",", ".")
		return &result
	}
	return nil
}
