package rest_websocket

import (
	"io"
	"log"
	"time"

	"github.com/gorilla/websocket"
)

func NewClient(addr string) (*Client, error) {
	conn, _, err := websocket.DefaultDialer.Dial(addr, nil)
	if err != nil {
		return nil, err
	}
	cl := &Client{
		conn: conn,
	}
	go cl.work()
	return cl, nil
}

type Client struct {
	conn             *websocket.Conn
	messagesIncoming map[int64]*Message
}

func (s *Client) SendMessage(mes *Message) (err error) {
	var writer io.WriteCloser
	if writer, err = s.conn.NextWriter(websocket.BinaryMessage); err != nil {
		return
	}
	err = mes.Write(writer)
	writer.Close()
	return
}

func (s *Client) work() {
	for {
		// Read message from server
		mType, r, err := s.conn.NextReader()
		if err != nil {
			log.Println(err)
			return
		}
		switch mType {
		case websocket.TextMessage, websocket.BinaryMessage:
			// Обработка текстового сообщения
			mes, err := ReadMessage(r)
			if err != nil {
				log.Println("data error: ", err)
				return
			}
			log.Println("RESPONSE", mes)
		case websocket.PingMessage:
			// Отправка Pong в ответ на Ping
			//s.sendLocker.Lock()
			err := s.conn.WriteControl(websocket.PongMessage, nil, time.Now().Add(time.Second))
			//s.sendLocker.Unlock()
			if err != nil {
				log.Println("pong write:", err)
				return
			}
		case websocket.CloseMessage:
			// Обработка закрытия соединения
			log.Println("websocket connection closed")
			return
		}
	}
}
