/*

 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 utils

import (
	"bufio"
	"fmt"
	"io"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/restmapper"
	"os"
	"sigs.k8s.io/yaml"
	"strings"
)

type PConfig struct {
	ParticipantId int64
}

// GetGVR 获取GVR
func GetGVR(clientSet *kubernetes.Clientset, gvk schema.GroupVersionKind) (schema.GroupVersionResource, error) {
	gr, err := restmapper.GetAPIGroupResources(clientSet)
	if err != nil {
		return schema.GroupVersionResource{}, err
	}

	mapper := restmapper.NewDiscoveryRESTMapper(gr)

	mapping, err := mapper.RESTMapping(gvk.GroupKind(), gvk.Version)
	if err != nil {
		return schema.GroupVersionResource{}, err
	}

	return mapping.Resource, nil
}

// UpdateParticipantId 更新本地配置文件ParticipantId
func UpdateParticipantId(filePath string, value string) error {
	file, err := os.OpenFile(filePath, os.O_RDWR, 0)
	if err != nil {
		return err
	}
	reader := bufio.NewReader(file)
	pos := int64(0)
	for {
		//读取每一行内容
		line, err := reader.ReadString('\n')
		if err != nil && err != io.EOF {
			fmt.Println("Read file error!", err)
			return err
		}
		//根据关键词覆盖当前行
		if strings.Contains(line, "ParticipantId") {
			bytes := []byte("ParticipantId: " + value)
			file.WriteAt(bytes, pos)
		}
		//每一行读取完后记录位置
		pos += int64(len(line))
		//读到末尾
		if err != nil && err == io.EOF {
			fmt.Println("File read ok!")
			break
		}
	}
	return nil
}

// GetParticipantId 获取本地配置文件中的ParticipantId
func GetParticipantId(filePath string) (int64, error) {
	pConfig := PConfig{}
	file, err := os.OpenFile(filePath, os.O_RDONLY, 0)
	if err != nil {
		return 0, err
	}
	bytes, err := io.ReadAll(file)
	if err != nil {
		return 0, err
	}
	yaml.Unmarshal(bytes, &pConfig)
	return pConfig.ParticipantId, nil
}
