package readcallsignal

import (
	"encoding/binary"

	"gitlab.com/ics_cinnamon/voicegateway/icserror"
	"gitlab.com/ics_cinnamon/voicegateway/icslog"
	"gitlab.com/ics_cinnamon/voicegateway/recorddata"
)

type CallSignal struct {
	ChannelID string
	ServerID  int
	AgentID   string
	Station   string
	//Station    int
	CreateTime int64
	EventType  string
	StartTime  int64
	EndTime    int64
	InOut      string
	CustID     string
}

type CallSignalP struct {
	CallSignal [recorddata.MAX_CALLSIGNAL_PACKET_LEN]byte
}

//call signal protocol offset. ex)buffer[id:len]
const (
	CHANNELID      = 0              //byte array 13
	CHANNELID_LEN  = 13             //byte array 13
	SERVERID       = CHANNELID + 13 //short 2
	SERVERID_LEN   = SERVERID + 2   //short 2
	AGENTID        = SERVERID + 2   //byte array 16
	AGENTID_LEN    = AGENTID + 16   //byte array 16
	STATION        = AGENTID + 16   //int 4
	STATION_LEN    = STATION + 4    //int 4
	CREATETIME     = STATION + 4    //long 8
	CREATETIME_LEN = CREATETIME + 8 //long 8
	EVENTTYPE      = CREATETIME + 8 //byte 1
	EVENTTYPE_LEN  = EVENTTYPE + 1  //byte 1
	STARTTIME      = EVENTTYPE + 1  //long 8
	STARTTIME_LEN  = STARTTIME + 8  //long 8
	ENDTIME        = STARTTIME + 8  //long 8
	ENDTIME_LEN    = ENDTIME + 8    //long 8
	INOUT          = ENDTIME + 8    //byte 1
	INOUT_LEN      = INOUT + 1      //byte 1
	CUSTID         = INOUT + 1      //byte 20
	CUSTID_LEN     = CUSTID + 20    //byte 20
)

func NewCallSignal(data []byte) *CallSignal {
	if len(data) > recorddata.MAX_CALLSIGNAL_PACKET_LEN {
		return nil
	}

	cs := CallSignal{}
	cs.parse(data)
	//fmt.Printf("%+v\n", cs)

	return &cs
}

func (cs *CallSignal) parse(data []byte) {
	defer func() {
		if err := recover(); err != nil {
			l := icslog.GetIcsLog()
			l.Print(icslog.LOG_LEVEL_WARN, -1, icserror.ICSERRRECORDDATAParsing.GetMessage())
		}
	}()

	cs.ChannelID = string(data[CHANNELID:CHANNELID_LEN])
	cs.ServerID = int(binary.LittleEndian.Uint16(data[SERVERID:SERVERID_LEN]))
	cs.AgentID = string(data[AGENTID:AGENTID_LEN])
	cs.Station = string(data[STATION:STATION_LEN])
	//cs.Station = int(binary.LittleEndian.Uint32(data[STATION:STATION_LEN]))
	cs.CreateTime = int64(binary.LittleEndian.Uint64(data[CREATETIME:CREATETIME_LEN]))
	cs.EventType = string(data[EVENTTYPE:EVENTTYPE_LEN][0])
	cs.StartTime = int64(binary.LittleEndian.Uint64(data[STARTTIME:STARTTIME_LEN]))
	cs.EndTime = int64(binary.LittleEndian.Uint64(data[ENDTIME:ENDTIME_LEN]))
	cs.InOut = string(data[INOUT:INOUT_LEN][0])
	cs.CustID = string(data[CUSTID:CUSTID_LEN])
}
