package rest_websocket

import (
	"log"
	"time"

	"git.ali33.ru/fcg-xvii/go-tools/json"
	"git.ali33.ru/fcg-xvii/rest"
)

/*
type IResponse interface {
	IsError() bool
	KeySet(key string, val any)
	FileSet(name string, file IReadCloserLen)
	Close()
	Send(writer any) IErrorArgs
}
*/

type Response struct {
	mes   *Message
	err   rest.IErrorArgs
	data  json.Map
	files map[string]rest.IReadCloserLen
}

func (s *Response) IsError() bool {
	return s.err != nil
}

func (s *Response) KeySet(key string, val any) {
	s.data[key] = val
}

func (s *Response) FileSet(name string, file rest.IReadCloserLen) {
	s.files[name] = file
}

func (s *Response) Close() {
	for _, file := range s.files {
		file.Close()
	}
	s.files = nil
}

func (s *Response) Send(writer any) rest.IErrorArgs {
	if s.IsError() {
		log.Println("ERRRRRRRRRRRRRRRRRRR")
		s.Close()
		s.data = s.err.Map()
		s.data["error"] = true
	}
	mes := &Message{
		id:      s.mes.id,
		command: s.mes.command,
		mType:   rest.RequestTypeAnswer,
		timeout: time.Now(),
		data:    s.data,
		files:   s.files,
	}
	log.Println("AAA", mes)
	err := s.mes.owner.sendMessage(mes)
	mes.Close()
	return err
}
