/*

 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"
	"sync"
	"time"
)

var clientsMutex sync.Mutex

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

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

// ReportHeartbeat 心跳请求
func (l *ReportHeartbeatLogic) ReportHeartbeat(in *pcmCore.ParticipantHeartbeatReq) (*pcmCore.HealthCheckResp, error) {
	//Participant服务key值以ps_开头
	key := fmt.Sprintf("ps_%s-%d", in.Address, in.ParticipantId)
	clientsMutex.Lock()
	defer clientsMutex.Unlock()
	setResult := l.svcCtx.RedisClient.HSet(context.Background(), key,
		map[string]interface{}{
			"address":       in.Address,
			"participantId": in.ParticipantId,
			"lastHeartbeat": time.Now().Unix(),
			"clientState":   "TRUE",
		})
	if setResult.Err() != nil {
		return nil, setResult.Err()
	}
	l.svcCtx.RedisClient.Expire(context.Background(), key, 30*time.Second)
	return &pcmCore.HealthCheckResp{
		Code: 200,
		Msg:  "ok",
	}, nil
}
