/**
 * @desc		TCP框架
 * ********************************************
 * @author		unphp <unphp@qq.com>
 * @date		2021-12-17
 * @copyright	ants 0.1
 * ********************************************
 */

package ants

import (
	"errors"
	"strings"
)

//NewRouter ...
func NewRouter() *Router {
	return &Router{
		routerMap: map[string]interface{}{},
	}
}

//Router 路由机制
type Router struct {
	routerMap          map[string]interface{}
	preMiddleHandler   []func(path string, params []byte) error
	afterMiddleHandler []func(path string, rs interface{}) interface{}
}

//AddPreMiddle 添加请求处理前置中间件
func (that *Router) AddPreMiddle(handler ...func(path string, params []byte) error) {
	if that.preMiddleHandler == nil {
		that.preMiddleHandler = []func(path string, params []byte) error{}
	}
	that.preMiddleHandler = append(that.preMiddleHandler, handler...)
}

//GetPreMiddle 获取前置中间件
func (that *Router) GetPreMiddle() []func(path string, params []byte) error {
	return that.preMiddleHandler
}

//AddAfterMiddle 添加请求后响应处理中间件
func (that *Router) AddAfterMiddle(handler ...func(path string, rs interface{}) interface{}) {
	if that.afterMiddleHandler == nil {
		that.afterMiddleHandler = []func(path string, rs interface{}) interface{}{}
	}
	that.afterMiddleHandler = append(that.afterMiddleHandler, handler...)
}

//GetAfterMiddle 获取后置中间件
func (that *Router) GetAfterMiddle() []func(path string, rs interface{}) interface{} {
	return that.afterMiddleHandler
}

//AddRouter 添加路由规则
func (that *Router) AddRouter(path string, router Handler) {
	if that.routerMap == nil {
		that.routerMap = map[string]interface{}{}
	}
	_path := strings.Trim(path, "/")
	if _err := that.pathCheck(_path); _err != nil {
		panic(_err.Error())
	}
	that.routerMap[_path] = router
}

//AddGroup 添加分组路由
func (that *Router) AddGroup(path string) RouterInterface {
	if that.routerMap == nil {
		that.routerMap = map[string]interface{}{}
	}
	_path := strings.Trim(path, "/")
	if _err := that.pathCheck(_path); _err != nil {
		panic(_err.Error())
	}
	_router := NewRouter()
	that.routerMap[_path] = _router
	return _router
}

//pathCheck 检测路由是否重复注册
func (that *Router) pathCheck(path string) error {
	_pathSlice := strings.Split(path, "/")
	for _i := len(_pathSlice); _i > 0; _i-- {
		_path := strings.Join(_pathSlice[0:_i], "/")
		if _, _ok := that.routerMap[_path]; _ok {
			return errors.New("add router [" + _path + "] repeated !")
		}
	}
	return nil
}

//RouteMatch 路由匹配
func (that *Router) RouteMatch(path string) (interface{}, bool) {
	if _router, _ok := that.routerMap[path]; _ok {
		return _router, _ok
	}
	return nil, false
}

//////////////////////////////////////////////////////////////////////////

////AntsRouter ...
//func NewAntsRouter() *AntsRouter {
//	return &AntsRouter{}
//}
//
////AntsActionRouter ...
//type AntsRouter struct {
//	ActionRouter    interface{}
//	ActionHanderMap map[string]Handler
//}
//
////AddRouter 添加
//func (that *AntsRouter) AddRouter(name string, router Handler) {
//	if that.ActionHanderMap == nil {
//		that.ActionHanderMap = make(map[string]Handler, 0)
//	}
//	that.ActionHanderMap[name] = router
//}
//
//func (that *AntsRouter) Handler(actionName string) (Handler, error) {
//	_hander, _ok := that.ActionHanderMap[actionName]
//	if !_ok {
//		return nil, errors.New("not this api's action![" + actionName + "]")
//	}
//	return _hander, nil
//}

////Route 路由：对action的路由分发控制
//func (that *AntsActionRouter) Route(action string, b []byte) (rsData interface{}) {
//	defer func() {
//		if err := recover(); err != nil {
//			rsData = errors.New(fmt.Sprint(err))
//			fmt.Println(err)
//			debug.PrintStack()
//			return
//		}
//	}()
//	//
//	if that.ActionRouter == nil {
//		// 当没有指定，则走通用接口
//		commonMethod := reflect.ValueOf(that).MethodByName(action)
//		if commonMethod.IsValid() {
//			in := make([]reflect.Value, 1)
//			in[0] = reflect.ValueOf(b)
//			call := commonMethod.Call(in)
//			rsData = call[0].Interface()
//		} else {
//			rsData = errors.New("Error::not this action of common's api ![" + action + "]")
//		}
//	} else {
//		// 如果指定了，则先判断指定的控制器是否存在这个action
//		appMethod := reflect.ValueOf(that.ActionRouter).MethodByName(action)
//		if appMethod.IsValid() {
//			in := make([]reflect.Value, 1)
//			in[0] = reflect.ValueOf(b)
//			callRs := appMethod.Call(in)
//			rsData = callRs[0].Interface()
//		} else {
//			commonMethod := reflect.ValueOf(that).MethodByName(action)
//			if commonMethod.IsValid() {
//				in := make([]reflect.Value, 1)
//				in[0] = reflect.ValueOf(b)
//				call := commonMethod.Call(in)
//				rsData = call[0].Interface()
//			} else {
//				rsData = errors.New("Error::not this action of private's api ![" + action + "]")
//			}
//		}
//	}
//	return
//}
