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

package ants

import (
	"errors"
	"strings"
)

//NewRequest 创建请求解析
func NewRequest(router RouterInterface) *Request {
	return &Request{
		router: router,
	}
}

//Request 请求解析
type Request struct {
	requestParams      []byte
	requestPath        string
	hander             Handler
	router             RouterInterface
	preMiddleHandler   []func(path string, params []byte) error
	afterMiddleHandler []func(path string, rs interface{}) interface{}
}

//AddPreMiddle ...
func (that *Request) 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...)
}

//AddAfterMiddle ...
func (that *Request) AddAfterMiddle(handler ...func(path string, rs interface{}) interface{}) {
	if that.afterMiddleHandler == nil {
		that.afterMiddleHandler = []func(path string, rs interface{}) interface{}{}
	}
	that.afterMiddleHandler = append(handler, that.afterMiddleHandler...)
}

//RouteMatch 对请求进行路由匹配
func (that *Request) RouteMatch(path string, bytes []byte) error {
	that.requestPath = strings.Trim(strings.TrimSpace(path), "/")
	that.requestParams = bytes
	//
	_pathSlice := strings.Split(that.requestPath, "/")
	if _err := that.match(_pathSlice); _err != nil {
		return _err
	}
	if that.hander == nil {
		return errors.New("not match router [" + that.requestPath + "]")
	}
	return nil
}

func (that *Request) match(pathSlice []string) error {
	_len := len(pathSlice)
	for _i := _len; _i > 0; _i-- {
		_path := strings.Join(pathSlice[0:_i], "/")
		//fmt.Println("======== route match =======", _i, _path)
		_router, _ok := that.router.RouteMatch(_path)
		if _ok {
			//
			switch _type := _router.(type) {
			case *Router:
				if _i == _len {
					return errors.New("")
				}
				//
				_preMiddleHandler := that.router.GetPreMiddle()
				if _preMiddleHandler != nil {
					that.AddPreMiddle(_preMiddleHandler...)
				}
				//
				_afterMiddleHandler := that.router.GetAfterMiddle()
				if _afterMiddleHandler != nil {
					that.AddAfterMiddle(_afterMiddleHandler...)
				}
				//
				that.router = _type
				//fmt.Println("======== route match AntsRouter =======", _i, _path)
				return that.match(pathSlice[_i:])
			case Handler:
				//fmt.Println("======== route match Handler =======", _i, _path)
				if _i == _len {
					that.hander = _type
					return nil
				}
			}
		}
	}
	return errors.New("not match router")
}

//Handler 执行匹配后的"处理方法"
func (that *Request) Handler() interface{} {
	//前置中间件
	if len(that.preMiddleHandler) > 0 {
		for _, _handler := range that.preMiddleHandler {
			if _err := _handler(that.requestPath, that.requestParams); _err != nil {
				return _err
			}
		}
	}
	//执行结果
	_rs := that.hander(that.requestParams)
	//后置中间件
	if len(that.afterMiddleHandler) > 0 {
		for _, _handler := range that.afterMiddleHandler {
			_rs = _handler(that.requestPath, _rs)
		}
	}
	return _rs
}
