/*

 Copyright (c) [2023] [pcm]
 [pcm-coordinator] is licensed under Mulan PSL v2.
 You can use this software according to the terms and conditions of the Mulan PSL v2.
 You may obtain a copy of Mulan PSL v2 at:
          http://license.coscl.org.cn/MulanPSL2
 THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 EITHER EXPaRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 See the Mulan PSL v2 for more details.

*/

package participantservicelogic

import (
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"gitlink.org.cn/JointCloud/pcm-coordinator/rpc/internal/svc"
	"gitlink.org.cn/JointCloud/pcm-coordinator/rpc/pcmCore"
	"time"
)

type ListParticipantLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListParticipantLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListParticipantLogic {
	return &ListParticipantLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// listParticipant 服务列表
func (l *ListParticipantLogic) ListParticipant(in *pcmCore.ParticipantTenant) (*pcmCore.ParticipantServiceResp, error) {
	// todo: add your logic here and delete this line
	rdb := l.svcCtx.RedisClient
	resp := pcmCore.ParticipantServiceResp{}
	clientInfo := pcmCore.ClientInfo{}
	//获取所有Participant的key值
	keys, err := l.svcCtx.RedisClient.Keys(context.Background(), "ps_*").Result()
	if err != nil {
		logx.Errorf("Error getting keys from Redis err: %v", err)
		return &pcmCore.ParticipantServiceResp{
			Code: 500,
			Msg:  fmt.Sprintf("get service list error %s", err),
		}, nil
	}
	for _, key := range keys {
		if err := rdb.HGetAll(l.ctx, key).Scan(&clientInfo); err != nil {
			logx.Errorf("get service err:", err)
			return &pcmCore.ParticipantServiceResp{
				Code: 500,
				Msg:  fmt.Sprintf("get service list error %s", err),
			}, nil
		}

		//最后心跳时间差值大于15s则标记服务为不健康
		if time.Now().Unix()-clientInfo.LastHeartbeat > 15 {
			clientInfo.ClientState = "UNKNOWN"
		}
		resp.Data = append(resp.Data, &clientInfo)
	}
	resp.Code = 200
	resp.Msg = "ok"
	return &resp, nil
}
