package router

import (
	"github.com/gorilla/mux"
	"zeevdiukman.com/zprox/pkg/helper"
)

func New() *MainRouter {
	r := &MainRouter{}
	r.setMux()
	return r
}

func (r *MainRouter) setMux() {
	r.Mux = mux.NewRouter()
}
func (mainRouter *MainRouter) AddGroupRouter(groupName string) *GroupRouter {
	s := mainRouter.Mux.NewRoute().Subrouter()
	groupRouter := &GroupRouter{
		Mux: s,
	}

	newMap := make(GroupRouters)
	helper.MapIter(mainRouter.GroupRouters, func(grName string, gr *GroupRouter) {
		newMap[grName] = gr
	})
	newMap[groupName] = groupRouter

	mainRouter.GroupRouters = newMap
	return groupRouter
}
func (mainRouter *MainRouter) GetGroupRouter(groupName string) *GroupRouter {
	return mainRouter.GroupRouters[groupName]
}
func (mainRouter *MainRouter) GetHostSubRouter(groupName string, domain string) *SubRouter {
	return mainRouter.GroupRouters[groupName].SubRouters[domain]
}
func (mainRouter *MainRouter) AddHostSubRouter(groupName string, domain string) *SubRouter {
	groupSubRouter := mainRouter.GroupRouters[groupName]
	newRoute := groupSubRouter.Mux.NewRoute()
	hostSubRouter := &SubRouter{
		Mux: newRoute.Host(domain).Subrouter(),
	}
	newMap := make(SubRouters)
	helper.MapIter(mainRouter.GroupRouters[groupName].SubRouters, func(grName string, gr *SubRouter) {
		newMap[grName] = gr
	})
	newMap[domain] = hostSubRouter
	mainRouter.GroupRouters[groupName].SubRouters = newMap
	return hostSubRouter
}

func (mainRouter *MainRouter) AddGroupSubRouter(groupName string, subRouterName string) *SubRouter {
	gsr := mainRouter.GetGroupRouter(groupName).Mux.NewRoute().Subrouter()
	subRouter := &SubRouter{
		Mux: gsr,
	}
	mainRouter.GroupRouters[groupName].SubRouters[subRouterName] = subRouter
	return subRouter
}

type MainRouter struct {
	GroupRouters GroupRouters
	Mux          *mux.Router
}

type GroupRouters map[string]*GroupRouter

type GroupRouter struct {
	SubRouters SubRouters
	Mux        *mux.Router
}

type SubRouters map[string]*SubRouter
type SubRouter struct {
	Mux *mux.Router
}
