package icssessionmanager

import (
	"strings"

	"gitlab.com/cinnamon/voiceagent/icserror"
	"gitlab.com/cinnamon/voiceagent/icslog"
	"gitlab.com/cinnamon/voiceagent/icspacketparser"
	"gitlab.com/cinnamon/voiceagent/icssvc"
	"gitlab.com/cinnamon/voiceagent/recorddata"
)

func (s *IcsSession) analyzeRTP(rtp *icspacketparser.RTP) *icserror.IcsError {
	l := icslog.GetIcsLog()

	RPT := rtp.GetPayloadType()
	SPT := s.GetPayloadType()
	if SPT == RPT {
		if s.VoiceNeter == nil {
			l.Print(icslog.LOG_LEVEL_ERROR, s.ID, icserror.ICSERRNETNotConnectError.GetMessage())
			return icserror.ICSERRNETNotConnectError
		}

		voicedata := recorddata.NewVoiceData()
		svc := icssvc.GetServiceStatus()
		conf := svc.GetIcsConfig()
		if strings.Compare(conf.HTTPConfig.SrcIP, rtp.SrcAddr.IPv4String) == 0 { //RX
			//if strings.Compare(conf.PbxConfig.PbxIp, rtp.SrcAddr.IPv4String) == 0 { //RX
			/*//////////////////
			s.rxFile.Write(rtp.Payload)
			*/ //////////////////
			pcm, err := s.RxConverter.Decode(rtp.Payload)
			if err != nil {
				l.Print(icslog.LOG_LEVEL_ERROR, s.ID, err.GetMessage())
				return err
			}

			if s.rxSeq == -1 {
				s.rxSeq = int(rtp.Seq)
			}

			voicedata.SetData(s.ServerID, s.Station, int32(rtp.Seq-uint16(s.rxSeq)), s.StartTimeStamp, "0", "0", pcm)

			wsize, err := s.VoiceNeter.Write(voicedata.GetData())
			if wsize == -1 || err != nil {
				l.Printf(icslog.LOG_LEVEL_ERROR, s.ID, "RTP send error-%v", err.GetError())
				return err
			}
		} else { //TX
			/*//////////////////
			s.txFile.Write(rtp.Payload)
			*/ //////////////////
			pcm, err := s.TxConverter.Decode(rtp.Payload)
			if err != nil {
				l.Print(icslog.LOG_LEVEL_ERROR, s.ID, err.GetMessage())
				return err
			}

			if s.txSeq == -1 {
				s.txSeq = int(rtp.Seq)
			}

			voicedata.SetData(s.ServerID, s.Station, int32(rtp.Seq-uint16(s.txSeq)), s.StartTimeStamp, "1", "0", pcm)

			wsize, err := s.VoiceNeter.Write(voicedata.GetData())
			if wsize == -1 || err != nil {
				//l.Printf(icslog.LOG_LEVEL_ERROR, s.ID, "RTP send error-%v", err.GetError())
				return err
			}
		}
	} else {
		l.Print(icslog.LOG_LEVEL_ERROR, s.ID, "NO same payload type!!!")
	}

	return nil
}
