package server

import (
	"common/log"
	"common/proto/sc/sc_pb"
	"common/proto/ss/grpc_pb"
	"gateway/internal/handler/ws_handler"
	"google.golang.org/protobuf/proto"
	"sync"
)

func (s *Server) ToClient(server grpc_pb.Gateway_ToClientServer) error {
	wg := &sync.WaitGroup{}
	wg.Add(1)
	go func() {
		defer wg.Done()
		defer func() {
			if err := recover(); err != nil {
				log.Errorf("Action panic: %v", err)
			}
		}()
		for {
			if args, err := server.Recv(); err != nil {
				return
			} else {
				if args.USN == -1 {

					//utils.WorkerPool(ws_handler.UserMgr.GetAllInterface(), func(task interface{}) {
					//	client := task.(*ws_handler.Client)
					//	client.WriteBytes(sc_pb.MessageID(args.MessageID), args.Payload)
					//})

					data, err := proto.Marshal(&sc_pb.Message{
						ID:      sc_pb.MessageID(args.MessageID),
						Payload: args.Payload,
					})
					if err != nil {
						log.Errorf("ToClient proto.Marshal error: %v", err)
						continue
					}
					for _, client := range ws_handler.UserMgr.GetAll() {
						client.WriteBytesPreMarshal(data)
					}

					//for _, client := range ws_handler.UserMgr.GetAll() {
					//	client.WriteBytes(sc_pb.MessageID(args.MessageID), args.Payload)
					//}
				} else {
					if client := ws_handler.UserMgr.GetByUSN(args.USN); client != nil {
						client.WriteBytes(sc_pb.MessageID(args.MessageID), args.Payload)
					}
				}
			}
		}
	}()
	wg.Wait()
	return server.SendAndClose(&grpc_pb.ToClientResp{})
}
