package main

import (
	"sparrow/pkg/protocol"
	"sparrow/pkg/rpcs"
	"sparrow/pkg/server"
)

type CoAPProvider struct {
}

func NewCoAPProvider() *CoAPProvider {
	return &CoAPProvider{}
}
func (mp *CoAPProvider) ValidateDeviceToken(deviceid string, token []byte) error {
	args := rpcs.ArgsValidateDeviceAccessToken{
		Id:          deviceid,
		AccessToken: token,
	}
	reply := rpcs.ReplyValidateDeviceAccessToken{}
	err := server.RPCCallByName(nil, rpcs.DeviceManagerName, "DeviceManager.ValidateDeviceAccessToken", args, &reply)
	if err != nil {
		server.Log.Errorf("validate device token error. deviceid : %v, token : %v, error: %v", deviceid, token, err)
		return err
	}
	return nil
}
func (mp *CoAPProvider) OnDeviceOnline(args rpcs.ArgsGetOnline) error {
	reply := rpcs.ReplyGetOnline{}
	err := server.RPCCallByName(nil, rpcs.DeviceManagerName, "DeviceManager.GetOnline", args, &reply)
	if err != nil {
		server.Log.Errorf("device online error. args: %v, error: %v", args, err)
	}

	return err
}
func (mp *CoAPProvider) OnDeviceOffline(deviceid string) error {
	args := rpcs.ArgsGetOffline{
		Id: deviceid,
	}
	reply := rpcs.ReplyGetOffline{}
	err := server.RPCCallByName(nil, rpcs.DeviceManagerName, "DeviceManager.GetOffline", args, &reply)
	if err != nil {
		server.Log.Errorf("device offline error. deviceid: %v, error: %v", deviceid, err)
	}

	return err
}
func (mp *CoAPProvider) OnDeviceHeartBeat(deviceid string) error {
	args := rpcs.ArgsDeviceId{
		Id: deviceid,
	}
	reply := rpcs.ReplyHeartBeat{}
	err := server.RPCCallByName(nil, rpcs.DeviceManagerName, "DeviceManager.HeartBeat", args, &reply)
	if err != nil {
		server.Log.Errorf("device heartbeat error. deviceid: %v, error: %v", deviceid, err)
	}
	return err
}
func (mp *CoAPProvider) OnDeviceMessage(deviceid string, msgtype string, message []byte) {
	server.Log.Infof("device {%v} message {%v} : %x", deviceid, msgtype, message)
	data := &protocol.Data{}
	err := data.UnMarshal(message)
	if err != nil {
		server.Log.Errorf("unmarshal data error : %v", err)
		return
	}
	server.Log.Debugf("data %#v", data.SubData)
}
