import {css, LitElement} from 'lit';
import '@vaadin/icon';
import '@vaadin/button';
import '@vaadin/text-field';
import '@vaadin/text-area';
import '@vaadin/form-layout';
import '@vaadin/progress-bar';
import '@vaadin/checkbox';
import '@vaadin/horizontal-layout';
import '@vaadin/grid';
import '@vaadin/grid/vaadin-grid-sort-column.js';

export class DemoChat extends LitElement {

    _stripHtml(html) {
        const div = document.createElement("div");
        div.innerHTML = html;
        return div.textContent || div.innerText || "";
    }

    connectedCallback() {

        const chatElementRef = document.getElementsByTagName("deep-chat")[0];
        const protocol = (window.location.protocol === 'https:') ? 'wss' : 'ws';

        const websocket = new WebSocket(protocol + '://' + window.location.host + '/customer-support-agent');
        // this handler is invoked when the component is loaded

        chatElementRef.onMessage = (body) => {
            if (body.message && body.message.role === 'user') {
                websocket.send(body.message.text);
            }};

        chatElementRef.connect = {
            stream: true,

            handler: (_, signals) => {
                try {

                    signals.onOpen(); // enables the user to send messages

                    websocket.onmessage = (message) => {
                        signals.onResponse({text: message.data});
                    };
                    websocket.onclose = () => {
                        signals.onClose(); // stops the user from sending messages
                    };
                    websocket.onerror = () => {
                        // 'Connection error' is a special string that will also display in Deep Chat
                        signals.onResponse({error: 'Connection error'});
                    };
                    // triggered when the user sends a message
                    // signals.newUserMessage.listener = (body) => {
                    //     websocket.send(JSON.stringify(body));
                    // };
                } catch (e) {
                    signals.onResponse({error: 'error'}); // displays an error message
                    signals.onClose(); // stops the user from sending messages
                }
            },
        };
    }
}


customElements.define('demo-deep-chat', DemoChat);