package manage

import (
	"code.hoteas.com/golang/hotime"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"golang.org/x/net/websocket"
	"io"
	"os"
	"path/filepath"
	"strings"
)

var ConfigPath = "config/config_manage.json"
var TptPath = "manageTpt"
var PkgDirPath = os.Getenv("GOPATH") + "/src/" + "go.hoteas.com/hotime/manage"

func Run() {

	appIns := hotime.Application{}
	//手动模式，
	appIns.SetConfig(ConfigPath)

	if _, e := os.Open(TptPath); e != nil {
		os.MkdirAll(TptPath, os.ModeDir)
		copyDir(PkgDirPath+"/"+appIns.Config.GetString("tpt"), TptPath)
	}

	appIns.Config["tpt"] = TptPath
	appIns.SetSession(hotime.CacheIns(&hotime.CacheMemory{}), hotime.CacheIns(&hotime.CacheMemory{}))
	appIns.SetCache(hotime.CacheIns(&hotime.CacheMemory{}))

	//快捷模式
	//appIns.SetDefault(func(err ...*hotime.Error) *sql.DB {
	//	query := appIns.Config.GetString("dbUser") + ":" + appIns.Config.GetString("dbPwd") +
	//		"@tcp(" + appIns.Config.GetString("dbHost") + ":" + appIns.Config.GetString("dbPort") + ")/" + appIns.Config.GetString("dbName") + "?charset=utf8"
	//	DB, e := sql.Open("mysql", query)
	//	if e != nil && len(err) != 0 {
	//		err[0].SetError(e)
	//	}
	//	return DB
	//})

	appIns.Run(hotime.Router{
		"app": hotime.Proj{
			"index": hotime.Ctr{
				"test": func(that *hotime.Context) {
					fmt.Println(that.Db.GetTag())
					//x := that.Db.Action(func(db hotime.HoTimeDB) bool {
					//
					//	db.Insert("user", hotime.Map{"unickname": "dasdas"})
					//
					//	return true
					//})
					that.Display(0, 1)
				},
				"websocket": func(that *hotime.Context) {
					hdler := websocket.Handler(func(ws *websocket.Conn) {
						for true {
							msg := make([]byte, 5120)
							n, err := ws.Read(msg)

							if err != nil {
								return
							}
							fmt.Printf("Receive: %s\n", msg[:n])

							send_msg := "[" + string(msg[:n]) + "]"
							m, err := ws.Write([]byte(send_msg))
							if err != nil {
								return
							}
							fmt.Printf("Send: %s\n", msg[:m])
						}
					})
					hdler.ServeHTTP(that.Resp, that.Req)
				},
			},
		},
	})
}

func copyDir(src string, dest string) {
	src_original := src
	err := filepath.Walk(src, func(src string, f os.FileInfo, err error) error {
		//fmt.Println(err)
		if f == nil {
			return err
		}
		if f.IsDir() {
			//          fmt.Println(f.Name())
			//          copyDir(f.Name(), dest+"/"+f.Name())
		} else {
			//fmt.Println(src)
			src = strings.Replace(src, "\\", "/", -1)
			//fmt.Println(src_original)
			//fmt.Println(dest)

			dest_new := strings.Replace(src, src_original, dest, -1)
			//fmt.Println(dest_new)
			//fmt.Println("CopyFile:" + src + " to " + dest_new)
			CopyFile(src, dest_new)
		}
		//println(path)
		return nil
	})
	if err != nil {
		fmt.Printf("filepath.Walk() returned %v\n", err)
	}
}

//egodic directories
func getFilelist(path string) {
	err := filepath.Walk(path, func(path string, f os.FileInfo, err error) error {
		if f == nil {
			return err
		}
		if f.IsDir() {
			return nil
		}
		println(path)
		return nil
	})
	if err != nil {
		fmt.Printf("filepath.Walk() returned %v\n", err)
	}
}
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
}

//copy file
func CopyFile(src, dst string) (w int64, err error) {
	srcFile, err := os.Open(src)
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	defer srcFile.Close()
	fmt.Println("dst:" + dst)
	dst_slices := strings.Split(dst, "\\")
	dst_slices_len := len(dst_slices)
	dest_dir := ""
	for i := 0; i < dst_slices_len-1; i++ {
		dest_dir = dest_dir + dst_slices[i] + "\\"
	}
	//dest_dir := getParentDirectory(dst)
	fmt.Println("dest_dir:" + dest_dir)
	b, err := PathExists(dest_dir)
	if b == false {
		err := os.Mkdir(dest_dir, os.ModePerm) //在当前目录下生成md目录
		if err != nil {
			fmt.Println(err)
		}
	}
	dstFile, err := os.Create(dst)

	if err != nil {
		fmt.Println(err.Error())
		return
	}

	defer dstFile.Close()

	return io.Copy(dstFile, srcFile)
}
