package events

import (
	"agent/commons/adata"
	"agent/commons/debug"
	"agent/defines/derrs"
	"io"
)

func EventFromStream(reader io.Reader, infinity bool, opts *EventResponse) (event IEvent, readed int64, err error) {
	//defer func() {
	//	if event != nil {
	//		log.Println("ParseRespReader: End, event:", event.Signature())
	//	}
	//	if err != nil {
	//		log.Println("ParseRespReader: End, error:", err)
	//	}
	//}()
	//log.Println("ParseRespReader: Start")

	pd := &responseReader{
		reader:              reader,
		maxDataSizeInMemory: 10 * 1024 * 1024,
	}

	if opts != nil {
		if len(opts.ToFilePath) > 0 {
			pd.dataFile = opts.ToFilePath
		}
		if opts.MaxDataSizeInMemory > 0 {
			pd.maxDataSizeInMemory = opts.MaxDataSizeInMemory
		}
	}

	if err := pd.parse(); err != nil {
		if !infinity && pd.readed == 0 {
			if !opts.Exist || opts.CanEmpty {
				return nil, pd.readed, nil
			}
		}
		debug.LogErr(err)
		return nil, pd.readed, err
	}

	if errData, ok := pd.ErrorData(); ok {
		return NewErrEvent(string(errData)), pd.readed, nil

	} else if pd.IsDataOnly() {
		var data adata.IData
		if len(pd.dataFile) > 0 {
			data = adata.NewDataFromFile(pd.dataFile)
		} else {
			data = adata.NewDataFromMem(pd.DataOnly())
		}
		return NewDataEvent(data), pd.readed, nil

	} else if pd.IsEvent() {
		var data adata.IData
		if len(pd.dataFile) > 0 {
			data = adata.NewDataFromFile(pd.dataFile)
		} else {
			data = adata.NewDataFromMem(pd.EventData())
		}
		event, err = NewEvent2(pd.EventBody(), data)
		return event, pd.readed, err
	}

	return nil, pd.readed, derrs.NewReadError()
}
