package helpers

import (
	"fmt"
	"net"
	"net/http"
	"strings"
	"path/filepath"
	"math/rand"
	"time"
	"strconv"
	"os"
	"io"
)

var r = rand.New(rand.NewSource(time.Now().UnixNano()))

func Ask(str string) bool {
	var input string
	fmt.Printf("-> %s (Y/n): ", str)
	fmt.Scanln(&input)
	input = strings.TrimSpace(input)
	input = strings.ToLower(input)
	if input != "y" && input != "" && input != "yes" {	
		return false
	}
	return true
}

func HTTPClient() *http.Client {
	transport := &http.Transport{
		DialContext: (&net.Dialer{
			Timeout: 10 * time.Second,
		}).DialContext,
		TLSHandshakeTimeout: 10 * time.Second,
	}
	return &http.Client{
		Transport: transport,
	}
}

func ToString(v interface{}) string {
	switch val := v.(type) {
	case int:
		return strconv.Itoa(val)
	case float64:
		return strconv.FormatFloat(val, 'f', -1, 64)
	case string:
		return val
	default:
		return ""
	}
}

func RandStr(n int) string {
    b := make([]byte, n)
    for i := range b {
        b[i] = byte(r.Intn(26) + 'a')
    }
    return string(b)
}

func CopyDir(src, dst string) error {
    return filepath.Walk(src, func(path string, info os.FileInfo, err error) error {
        if err != nil {
            return err
        }

        rel, err := filepath.Rel(src, path)
        if err != nil {
            return err
        }

        target := filepath.Join(dst, rel)

        mode := info.Mode()

        switch {
        case mode&os.ModeSymlink != 0:
            link, err := os.Readlink(path)
            if err != nil {
                return err
            }
            if err := os.RemoveAll(target); err != nil {
                return err
            }
            return os.Symlink(link, target)

        case info.IsDir():
            return os.MkdirAll(target, 0755)

        default:
            return CopyFile(path, target)
        }
    })
}

func CopyFile(src, dst string) error {
	in, err := os.Open(src)
	if err != nil {
		return err
	}
	defer in.Close()

	out, err := os.Create(dst)
	if err != nil {
		return err
	}
	defer out.Close()

	_, err = io.Copy(out, in)
	if err != nil {
		return err
	}

	si, err := os.Stat(src)
	if err != nil {
		return err
	}
	return os.Chmod(dst, si.Mode())
}
