package stream_client

import (
	"common/log"
	"common/net/grpc/service"
	"context"
	"google.golang.org/grpc"
	"google.golang.org/protobuf/proto"
)

var sceneServerM map[int64]map[SceneFun]grpc.ClientStream // map[sid]map[方法名]流连接

type SceneFun int

const (
	FunAction SceneFun = iota
)

func init() {
	sceneServerM = make(map[int64]map[SceneFun]grpc.ClientStream)
}

func findSceneBySID(sid int64, fun SceneFun) (grpc.ClientStream, error) {
	g := sceneServerM[sid]
	if g == nil {
		g = make(map[SceneFun]grpc.ClientStream)
		sceneServerM[sid] = g
	}
	sceneLink := g[fun]
	if sceneLink == nil {
		sceneClient, err := service.SceneNewClient(sid)
		if err != nil {
			log.Errorf("cannot find sceneClient: %v", err)
			return nil, err
		}
		var link grpc.ClientStream
		switch fun {
		case FunAction:
			link, err = sceneClient.Action(context.Background())
		}
		if err != nil {
			log.Errorf("findSceneBySID %v err: %v, sid: %v", fun, err, sid)
			return nil, err
		}
		g[fun] = link
		sceneLink = link
	}
	return sceneLink, nil
}

func SendMessageToScene(sid int64, fun SceneFun, msg proto.Message, re ...bool) error {
	stream, err := findSceneBySID(sid, fun)
	if err != nil {
		return err
	}
	if err = stream.SendMsg(msg); err != nil {
		if re == nil || !re[0] {
			_ = stream.CloseSend()
			delete(sceneServerM[sid], fun)
			return SendMessageToScene(sid, fun, msg, true)
		}
		return err
	}
	return nil
}
