package NatsServer

import (
	"ColdVerify_local/lib"
	"ColdVerify_local/logs"
	"ColdVerify_local/models/Task"
	"errors"
	"github.com/vmihailenco/msgpack/v5"
	"time"
)

func Update_Task(v Task.Task) error {
	logs.Debug("Nats =>", lib.FuncName(), v)

	b, err := msgpack.Marshal(&v)
	if err != nil {
		panic(err)
	}

	msg, err := lib.Nats.Request("ColdVerify_Server_Update_Task", b, 3*time.Second)
	if err != nil {
		return err
	}

	type T_R struct {
		Code int16     `xml:"Code"`
		Msg  string    `xml:"Msg"`
		Data Task.Task `xml:"Data"`
	}
	var t_R T_R

	err = msgpack.Unmarshal(msg.Data, &t_R)
	if err != nil {
		return err
	}
	if t_R.Code != 200 {
		return errors.New(t_R.Msg)
	}

	return nil

}

func Read_Task(T_task_id string) (task Task.Task, err error) {
	logs.Println("Nats =>", lib.FuncName(), T_task_id)

	msg, err := lib.Nats.Request("ColdVerify_Server_Read_Task", []byte(T_task_id), 3*time.Second)
	if err != nil {
		return task, err
	}

	type T_R struct {
		Code int16     `xml:"Code"`
		Msg  string    `xml:"Msg"`
		Data Task.Task `xml:"Data"`
	}
	var t_R T_R

	err = msgpack.Unmarshal(msg.Data, &t_R)
	if err != nil {
		return task, err
	}
	if t_R.Code != 200 {
		return task, errors.New(t_R.Msg)
	}

	return t_R.Data, nil

}
