package stack

import (
	"context"
	"encoding/xml"
	"fmt"
	"gb-cms/common"
	"github.com/ghettovoice/gosip/sip"
)

const (
	QueryRecordFormat = "<?xml version=\"1.0\"?>\r\n" +
		"<Query>\r\n" +
		"<CmdType>RecordInfo</CmdType>\r\n" +
		"<SN>%d</SN>\r\n" +
		"<DeviceID>%s</DeviceID>\r\n" +
		"<StartTime>%s</StartTime>\r\n" +
		"<EndTime>%s</EndTime>\r\n" +
		"<Type>%s</Type>\r\n" +
		"</Query>\r\n"

	SeekBodyFormat = "PLAY RTSP/1.0\r\n" + "CSeq: %d\r\n" + "Range: npt=%d-\r\n"
)

var (
	RtspMessageType sip.ContentType = "application/RTSP"
)

type QueryRecordInfoResponse struct {
	XMLName    xml.Name   `xml:"Response"`
	CmdType    string     `xml:"CmdType"`
	SN         int        `xml:"SN"`
	DeviceID   string     `xml:"DeviceID"`
	SumNum     int        `xml:"SumNum"`
	DeviceList RecordList `xml:"RecordList"`
	BaseMessage
}

type RecordList struct {
	Num            int          `xml:"Num,attr"`
	Devices        []RecordInfo `xml:"Item"`
	cancelFunction *context.CancelFunc
}

type RecordInfo struct {
	DeviceID       string `xml:"DeviceID"`
	Name           string `xml:"Name"`
	FilePath       string `xml:"FilePath" json:"filePath"`
	Address        string `xml:"Address"`
	StartTime      string `xml:"StartTime" json:"startTime"`
	EndTime        string `xml:"EndTime" json:"endTime"`
	Secrecy        string `xml:"Secrecy"`
	Type           string `xml:"Type"`
	RecorderID     string `xml:"RecorderID" json:"recorderId"`
	FileSize       uint64 `xml:"FileSize" json:"fileSize"`
	RecordLocation string `xml:"RecordLocation"`
	StreamNumber   int    `xml:"StreamNumber"`

	ResourceType   string `xml:"ResourceType" json:"type"`
	ResourceId     string `xml:"ResourceId" json:"resourceId"`
	UserId         string `xml:"UserId" json:"userId"`
	UserName       string `xml:"UserName" json:"userName"`
	ResourceName   string `xml:"ResourceName" json:"resourceName"`
	ResourceLength string `xml:"ResourceLength" json:"resourceLength"`
	ImportTime     string `xml:"ImportTime" json:"importTime"`
	ResourceUrl    string `xml:"ResourceUrl" json:"resourceUrl"`
	Remark         string `xml:"Remark" json:"remark"`
	Level          string `xml:"Level" json:"level"`
	BootTime       string `xml:"BootTime" json:"bootTime"`
	ShutdownTime   string `xml:"ShutdownTime" json:"shutdownTime"`
}

func (d *Device) DoQueryRecordList(channelId, startTime, endTime string, sn int, type_ string) error {
	body := fmt.Sprintf(QueryRecordFormat, sn, channelId, startTime, endTime, type_)
	request := d.BuildMessageRequest(channelId, body)
	common.SipStack.SendRequest(request)
	return nil
}
