package protocol

import (
	json2 "encoding/json"
	jsoniter "github.com/json-iterator/go"
)

var json = jsoniter.ConfigFastest

var (
	SUCCESS uint8 = 0
	FAILED  uint8 = 1

	SUCCESS_STR = "Successed"
	FAILED_STR  = "Failed"
)

type Header struct {
	Id   string `json:"id"`            //设备编码[网关、一键呼叫、灯控、环境传感器、摄象机等]
	Seq  uint64 `json:"seq"`           //消息序号
	Gid  string `json:"gid,omitempty"` //网关ID，没有可不填写
	Time string `json:"time"`          //时间
}

func (o *Header) SetHeaderData(id, gid string, seq uint64) {
	o.Id = id
	o.Gid = gid
	o.Seq = seq
	o.Time = BJNow().Format("2006-01-02 15:04:05")
}

type StateError struct {
	State uint8  `json:"state"`           //状态
	Error string `json:"error,omitempty"` //错误内容
}

func NewStateError(err error) *StateError {
	var r StateError
	if err != nil {
		r.State = FAILED
		r.Error = err.Error()
	} else {
		r.State = SUCCESS
		r.Error = SUCCESS_STR
	}
	return &r
}

func (o *StateError) SetStateErrorData(err error) {
	if err != nil {
		o.State = FAILED
		o.Error = err.Error()
	} else {
		o.State = SUCCESS
		o.Error = SUCCESS_STR
	}
}

type Pack_Ack struct {
	Header
	Data StateError `json:"data"`
}

func (o *Pack_Ack) EnCode(id, gid string, seq uint64, err error) (string, error) {
	o.Header.SetHeaderData(id, gid, seq)
	o.Data.SetStateErrorData(err)
	return json.MarshalToString(o)
}

func (o *Pack_Ack) DeCode(message string) error {
	return json.UnmarshalFromString(message, o)
}

type IDObject struct {
	Id uint `json:"id"`
}

type Pack_IDObject struct {
	Header
	Data IDObject `json:"data"`
}

func (o *Pack_IDObject) EnCode(gid string, seq uint64, id uint) (string, error) {
	o.Header.SetHeaderData(gid, gid, seq)
	o.Data.Id = id
	return json.MarshalToString(o)
}

func (o *Pack_IDObject) DeCode(message string) error {
	return json.UnmarshalFromString(message, o)
}

type UploadData struct {
	StateError
	Tid  uint16             `json:"tid"`
	Data map[uint16]float64 `json:"data,omitempty"`
}

type Pack_UploadData struct {
	Header
	Data UploadData `json:"data"`
}

func (o *Pack_UploadData) EnCode(id, gid string, seq uint64, err error, tid uint16, data map[uint16]float64) (string, error) {
	o.Header.SetHeaderData(id, gid, seq)
	o.Data.StateError.SetStateErrorData(err)
	o.Data.Tid = tid
	o.Data.Data = data
	marshal, err1 := json2.Marshal(o)
	return string(marshal), err1
	//return json.MarshalToString(o)
}
func (o *Pack_UploadData) DeCode(message string) error {
	return json.UnmarshalFromString(message, o)
}

type ControlData struct {
	Tid uint16 `json:"tid"`
	Sid uint16 `json:"sid"`
	Val uint   `json:"val"`
}
type Pack_ControlData struct {
	Header
	Data ControlData `json:"data"`
}

func (o *Pack_ControlData) EnCode(id, gid string, seq uint64, tid, sid uint16, val uint) (string, error) {
	o.Header.SetHeaderData(id, gid, seq)
	o.Data.Tid = tid
	o.Data.Sid = sid
	o.Data.Val = val
	return json.MarshalToString(o)
}
func (o *Pack_ControlData) DeCode(message string) error {
	return json.UnmarshalFromString(message, o)
}
