// Copyright 2021 CloudWeGo Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

package main

import (
	"context"
	"log"
	"net"
	"sync"

	"github.com/cloudwego/kitex-examples/kitex_gen/api"
	"github.com/cloudwego/kitex-examples/kitex_gen/api/echo"
	"github.com/cloudwego/kitex/pkg/klog"
	"github.com/cloudwego/kitex/server"
)

var (
	_ api.Echo = &Echo0Impl{}
	_ api.Echo = &Echo1Impl{}
)

// Echo0Impl implements the last service interface defined in the IDL.
type Echo0Impl struct{}

// Echo implements the Echo interface.
func (s *Echo0Impl) Echo(ctx context.Context, req *api.Request) (resp *api.Response, err error) {
	klog.Info("echo0 called")
	return &api.Response{Message: req.Message}, nil
}

// Echo1Impl implements the last service interface defined in the IDL.
type Echo1Impl struct{}

// Echo implements the Echo interface.
func (s *Echo1Impl) Echo(ctx context.Context, req *api.Request) (resp *api.Response, err error) {
	klog.Info("echo1 called")
	return &api.Response{Message: req.Message}, nil
}

func main() {
	svr0 := echo.NewServer(new(Echo0Impl), server.WithServiceAddr(&net.TCPAddr{Port: 8888}))
	svr1 := echo.NewServer(new(Echo1Impl), server.WithServiceAddr(&net.TCPAddr{Port: 8889}))
	var wg sync.WaitGroup
	wg.Add(2)
	go func() {
		defer wg.Done()
		if err := svr0.Run(); err != nil {
			log.Println("server0 stopped with error:", err)
		} else {
			log.Println("server0 stopped")
		}
	}()
	go func() {
		defer wg.Done()
		if err := svr1.Run(); err != nil {
			log.Println("server1 stopped with error:", err)
		} else {
			log.Println("server1 stopped")
		}
	}()
	wg.Wait()
}
