/*
Copyright © 2021 Manuel Kieweg <mail@manuelkieweg.de>
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

3. Neither the name of the copyright holder nor the names of its contributors
   may be used to endorse or promote products derived from this software
   without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/

package cmd

import (
	"context"
	"net"
	"os"
	"os/signal"
	"syscall"

	pb "code.fbi.h-da.de/danet/gosdn/api/go/gosdn/csbi"
	"code.fbi.h-da.de/danet/gosdn/api/go/gosdn/transport"
	log "github.com/sirupsen/logrus"
	"github.com/spf13/cobra"
	"google.golang.org/grpc"
)

// helloCmd represents the hello command.
var helloCmd = &cobra.Command{
	Use:   "hello",
	Short: "serves Hello service for testing purposes",
	Args:  cobra.MaximumNArgs(1),
	Run: func(cmd *cobra.Command, args []string) {
		bind := ":55055"
		if len(args) > 0 {
			bind = ":" + args[0]
		}
		Run(bind)
	},
}

var stopChan chan os.Signal

func init() {
	rootCmd.AddCommand(helloCmd)
	stopChan = make(chan os.Signal)
	signal.Notify(stopChan, os.Interrupt, syscall.SIGTERM)
}

type server struct {
	pb.UnimplementedCsbiServiceServer
}

func (s server) Hello(ctx context.Context, syn *pb.Syn) (*pb.Ack, error) {
	ack := &pb.Ack{
		Timestamp: 0,
		TransportOption: &transport.TransportOption{
			Address:  "localhost:7030",
			Username: "test",
			Password: "test",
			Tls:      false,
			TransportOption: &transport.TransportOption_GnmiTransportOption{
				GnmiTransportOption: &transport.GnmiTransportOption{},
			},
		},
	}
	return ack, nil
}

// Run bootstraps the orchestrator and waits for the shutdown signal.
func Run(bindAddr string) {
	g := grpc.NewServer()
	s := &server{}

	pb.RegisterCsbiServiceServer(g, s)
	log.Infof("starting to listen on %s", bindAddr)
	listen, err := net.Listen("tcp", bindAddr)
	if err != nil {
		log.Fatal(err)
	}

	go func() {
		log.Info("starting to serve")
		if err := g.Serve(listen); err != nil {
			log.Fatal(err)
		}
	}()

	log.WithFields(log.Fields{}).Info("initialisation finished")
	<-stopChan
}
