package main

import (
	"flag"
	"fmt"
	"net"
	"os"
	"path/filepath"

	pb "code.fbi.h-da.de/danet/gosdn/api/go/gosdn/plugin-registry"
	"code.fbi.h-da.de/danet/gosdn/controller/interfaces/plugin"
	"github.com/google/uuid"
	"google.golang.org/grpc"
)

const (
	pluginFilePath = "plugins"
	pluginName     = "bundled_plugin.zip"
)

func main() {
	socket := flag.String("socket", "9000", "port for the grpc socket, e.g. 9000")
	flag.Parse()

	lislisten, err := net.Listen("tcp", fmt.Sprintf(":%s", *socket))
	if err != nil {
		panic(err)
	}

	pr := registerPlugins()

	grpcServer := grpc.NewServer()
	server := NewServer(pr)
	pb.RegisterPluginRegistryServiceServer(grpcServer, server)
	if err := grpcServer.Serve(lislisten); err != nil {
		panic(err)
	}
}

// TODO: The registration of plugins should result in the same UUID's even
// after reboot. Therefore it would make sense to use a database. For a simple
// prototype this is currently hardcoded.
func registerPlugins() *PluginRegistry {
	files, err := os.ReadDir(pluginFilePath)
	if err != nil {
		panic(err)
	}

	pr := &PluginRegistry{}

	for i, file := range files {
		fmt.Printf("File %+v\n", file)

		if file.IsDir() {
			manifest, err := plugin.ReadManifestFromFile(filepath.Join(pluginFilePath, file.Name()))
			if err != nil {
				panic(err)
			}

			var id uuid.UUID
			switch i {
			case 0:
				id = uuid.MustParse("e2c358b3-6482-4010-b0d8-679dff73153b")
			case 1:
				id = uuid.MustParse("d1c269a2-6482-4010-b0d8-679dff73153b")
			case 2:
				id = uuid.MustParse("f3b474c2-6482-4010-b0d8-679dff73153b")
			default:
				break
			}

			plugin := &Plugin{
				ID:       id,
				Path:     filepath.Join(pluginFilePath, file.Name(), pluginName),
				Manifest: manifest,
			}

			pr.Plugins = append(pr.Plugins, plugin)
		}
	}

	return pr
}
