package main

import (
	"context"
	"crypto/rsa"
	"encoding/gob"
	"net/http"
	"net/http/httputil"

	"github.com/gorilla/mux"
	"github.com/zeevdiukman/go-helper"
	"github.com/zeevdiukman/zprox/internal/config"
	"github.com/zeevdiukman/zprox/internal/proxy"
	"golang.org/x/oauth2"
)

func init() {
	gob.RegisterName("oauth2_token_pointer", &oauth2.Token{})
	gob.RegisterName("rsa_public_key_pointer", &rsa.PublicKey{})
}

func Init() {
	config.Data.InitContext(context.Background())

}

func main() {
	Init()
	helper.AppRunner(true, func() {
		rp := &httputil.ReverseProxy{}
		handlers := make(map[string]func(string, string) http.HandlerFunc)
		entryPointsMuxRouters := make(map[string]*mux.Router)
		activeEntryPoints := make(map[string]bool)
		config.Data.EntryPoints.ForEach(func(epName string, epData *config.EntryPoint) {
			activeEntryPoints[epName] = false
			config.Data.Routers.ForEach(func(name string, data *config.Router) string {
				if data.EntryPoint == epName {
					entryPointsMuxRouters[epName] = mux.NewRouter()
					activeEntryPoints[epName] = true
				}
				return "continue"
			})
		})

		config.Data.Routers.ForEachByPriority(func(routerName string, routerData *config.Router) {
			isActiveEntryPoint := activeEntryPoints[routerData.EntryPoint]
			if isActiveEntryPoint {
				epr := entryPointsMuxRouters[routerData.EntryPoint]
				// buildAuthRoutes(epr, routerData)
				handlers[routerData.EntryPoint] = proxy.ReverseProxypHandler(epr, rp, routerData)
				buildAuthRoutes(epr, routerData) //Must be be built before the routes
				BuildRoutes(routerData, handlers, epr)

			}
		})
		config.Data.EntryPoints.ForEach(func(epName string, epData *config.EntryPoint) {
			if activeEntryPoints[epName] {
				if _, ok := entryPointsMuxRouters[epName]; ok {
					router := entryPointsMuxRouters[epName]
					BuildEntryPoint(epData, router)
				}
			}

		})
		helper.StartTestHTTPServer(3001, "albert")
	})
}
