package file_server_sdk

import (
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
	"sync"
)

var (
	persistent = "api/v1/files/persistent" //文件持久化路径
)

type persistentStruct struct {
	Hash string `json:"hash"`
}

type Config struct {
	Host   string
}

type ConfigHandle struct {
	Host   string
}

var (
	once sync.Once
	internalHandle  *ConfigHandle
)

func (c *Config) Init() {
	//代码运行中需要的时候执行，且只执行一次
	once.Do(func() {
		internalHandle = &ConfigHandle{
			Host: c.Host,
		}
	})
}

// GetHandle get handle
func GetHandle() *ConfigHandle {
	return internalHandle
}

//HandlePersistent 设置文件持久化
func (c *ConfigHandle) HandlePersistent(hash string) error {
	if hash == "" {
		return errors.New("缺少请求参数")
	}
	param := persistentStruct{
		Hash: hash,
	}
	s, err := json.Marshal(param)
	if err != nil {
		return err
	}
	url := fmt.Sprintf("%s/%s", c.Host, persistent)
	reqBody := strings.NewReader(string(s))
	req, err := http.NewRequest(http.MethodPut, url, reqBody)
	if err != nil {
		return err
	}
	req.Header.Set("Content-type", "application/json")
	client := &http.Client{}
	response, err := client.Do(req)
	if err != nil {
		return err
	}
	_, err = ioutil.ReadAll(response.Body)
	if err != nil {
		return err
	}
	return nil
}
