package utils

import (
	"fmt"
	"os"
	"time"
)

const (
	color_red = uint8(iota + 91)
	color_green
	color_yellow
	color_blue
	color_magenta //洋红

	// info = "[INFO]"
	// trac = "[TRAC]"
	// erro = "[ERRO]"
	// warn = "[WARN]"
	// succ = "[SUCC]"
)

// 根据 https://github.com/liyu4/chill 修改的
// see complete color rules in document in https://en.wikipedia.org/wiki/ANSI_escape_code#cite_note-ecma48-13
func TraceLog(format string, a ...interface{}) {
	fmt.Println(formatLog(yellow(fmt.Sprintf(format, a...))))
}

func InfoLog(format string, a ...interface{}) {
	fmt.Println(formatLog(blue(fmt.Sprintf(format, a...))))
}

func SuccessLog(format string, a ...interface{}) {
	fmt.Println(formatLog(green(fmt.Sprintf(format, a...))))
}

func WarningLog(format string, a ...interface{}) {
	fmt.Println(formatLog(magenta(fmt.Sprintf(format, a...))))
}

func ErrorLog(format string, a ...interface{}) {
	fmt.Println(formatLog(red(fmt.Sprintf(format, a...))))
}

func red(s string) string {
	return fmt.Sprintf("\x1b[%dm%s\x1b[0m", color_red, s)
}

func green(s string) string {
	return fmt.Sprintf("\x1b[%dm%s\x1b[0m", color_green, s)
}

func yellow(s string) string {
	return fmt.Sprintf("\x1b[%dm%s\x1b[0m", color_yellow, s)
}

func blue(s string) string {
	return fmt.Sprintf("\x1b[%dm%s\x1b[0m", color_blue, s)
}

func magenta(s string) string {
	return fmt.Sprintf("\x1b[%dm%s\x1b[0m", color_magenta, s)
}

func formatLog(prefix string) string {
	return time.Now().Format("[2006/01/02 15:04:05]") + " " + prefix + " "
}

func Mkdir(dir string) {
	// 创建文件夹
	exist, err := PathExists(dir)
	if err != nil {
		fmt.Println(err.Error())
	} else {
		if exist {
			fmt.Println(dir + "文件夹已存在!")
		} else {
			// 文件夹名称,权限
			err := os.Mkdir(dir, os.ModePerm)
			if err != nil {
				fmt.Println(dir+"文件夹创建失败:", err.Error())
			} else {
				fmt.Println(dir + "文件夹创建成功!")
			}
		}
	}
}

func PathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}