package utils

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"os"
	"path/filepath"

	uuid "github.com/satori/go.uuid"
)

// Md5 md5加密算法
func Md5(s string) string {
	h := md5.New()
	h.Write([]byte(s))
	cipherStr := h.Sum(nil)
	return fmt.Sprintf("%s", hex.EncodeToString(cipherStr))
}

// CreateIfNotExist 创建目录
func CreateIfNotExist(filename string) error {
	dir := filepath.Dir(filename)
	if dir != "" {
		exists, _ := Exists(dir)
		if !exists {
			err := os.MkdirAll(dir, os.ModePerm)
			if err != nil {
				return err
			}
		}
	}
	return nil
}

// Exists ...
func Exists(filename string) (bool, error) {
	exists := true
	_, err := os.Stat(filename)
	if err != nil {
		if os.IsNotExist(err) {
			exists = false
		}
	}
	return exists, err
}

// UUID uuid
func UUID() string {
	s := uuid.NewV4()
	return s.String()
}
