package icsws

import (
	"net/url"

	"github.com/gorilla/websocket"
	"gitlab.com/cinnamon/voiceagent/icserror"
)

type WSClient struct {
	Conn      *websocket.Conn
	configStr string
}

func NewWSClient(host, path string) *WSClient {
	client := WSClient{}

	u := url.URL{Scheme: "ws", Host: host, Path: path}
	client.configStr = u.String()

	return &client
}

func (client *WSClient) Connect() *icserror.IcsError {
	conn, _, err := websocket.DefaultDialer.Dial(client.configStr, nil)
	//conn, resp, err := websocket.DefaultDialer.Dial(client.configStr, nil)
	if err != nil {
		icserror.ICSERRWEBSOCKETConnectFailError.SetError(err)
		//fmt.Println(resp)
		return icserror.ICSERRWEBSOCKETConnectFailError
	}

	client.Conn = conn

	return nil
}

func (client *WSClient) Close() *icserror.IcsError {
	if client.Conn == nil {
		return icserror.ICSERRWEBSOCKETNotConnectError
	}

	err := client.Conn.Close()
	if err != nil {
		icserror.ICSERRWEBSOCKETNotClose.SetError(err)
		return icserror.ICSERRWEBSOCKETNotClose
	}

	return nil
}

func (client WSClient) Read() ([]byte, *icserror.IcsError) {
	if client.Conn == nil {
		return nil, icserror.ICSERRWEBSOCKETNotConnectError
		//return []byte(""), icserror.ICSERRWEBSOCKETNotConnectError
	}

	mtype, data, err := client.Conn.ReadMessage()
	if err != nil {
		icserror.ICSERRWEBSOCKETReadError.SetError(err)
		return nil, icserror.ICSERRWEBSOCKETReadError
		//return []byte(""), icserror.ICSERRWEBSOCKETReadError
	}

	if mtype != 1 { //only text type
		return nil, icserror.ICSERRWEBSOCKETSupportedMsgType
	}

	return data, nil
}

func (client WSClient) Write(message string) *icserror.IcsError {
	if client.Conn == nil {
		return icserror.ICSERRWEBSOCKETNotConnectError
	}
	if len(message) <= 0 {
		return icserror.ICSERRInvalidParam
	}

	err := client.Conn.WriteMessage(1, []byte(message))
	if err != nil {
		icserror.ICSERRWEBSOCKETWriteError.SetError(err)
		return icserror.ICSERRWEBSOCKETWriteError
	}

	return nil
}

func (client WSClient) WriteData(data []byte) *icserror.IcsError {
	if client.Conn == nil {
		return icserror.ICSERRWEBSOCKETNotConnectError
	}
	if len(data) <= 0 {
		return icserror.ICSERRInvalidParam
	}

	err := client.Conn.WriteMessage(1, data)
	if err != nil {
		icserror.ICSERRWEBSOCKETWriteError.SetError(err)
		return icserror.ICSERRWEBSOCKETWriteError
	}

	return nil
}
