$(document).ready(function() {
    var currentVideoSessionId; //essioni id of current video session, if session in action
    var customerName; //name of customer
    var service; //name of service

    /**
     * customer name and service name from document
     */
    var $settings = $('#settings-container');
    var $serverUrl = $('#setting-server-url');
    var $customerName = $('#setting-customer-name');
    var $serviceCode = $('#setting-service-code');
    var $submit = $('#settings-submit');
    var videoCamera = true;
    var microphone = true;
    var monitor; //session monitor events

    var $videoLay = $('#videoLayout'); //video layout
    $videoLay.hide();

    var $info = $('#info'); //text area - read only for "log"
    $info.hide();

    var $debugOn = $('#debugOn'); //enable library log button
    $debugOn.hide();

    var $debugOff = $('#debugOff'); //disable library log
    $debugOff.hide();

    var $connectionTest = $('#connectionTest'); //echotest button
    $connectionTest.hide();

    var $devicesStatus = $('#devicesStatus'); //echotest button
    $devicesStatus.hide();

    var $videoChannelSession = $('#videoChannelSession'); // video channel session button
    $videoChannelSession.hide();

    var $videoControls = $('#videoControls'); //video controls
    $videoControls.html(
        '<button id="circle-video" style="border-radius: 100%; width: 50px;height: 50px;background-color:rgb(0, 25, 58);margin-left:45%;opacity: 0.5;">' +
            '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 512"width="25px"height="25px"><path d="M633.8 458.1l-55-42.5c15.4-1.4 29.2-13.7 29.2-31.1v-257c0-25.5-29.1-40.4-50.4-25.8L448 177.3v137.2l-32-24.7v-178c0-26.4-21.4-47.8-47.8-47.8H123.9L45.5 3.4C38.5-2 28.5-.8 23 6.2L3.4 31.4c-5.4 7-4.2 17 2.8 22.4L42.7 82 416 370.6l178.5 138c7 5.4 17 4.2 22.5-2.8l19.6-25.3c5.5-6.9 4.2-17-2.8-22.4zM32 400.2c0 26.4 21.4 47.8 47.8 47.8h288.4c11.2 0 21.4-4 29.6-10.5L32 154.7v245.5z"fill="#fff"/></svg>' +
            '</button>' +
            '<button id="circle-audio" style="border-radius: 100%;opacity: 0.5;background-color:rgb(0, 25, 58);width: 50px;height: 50px;margin-left:2%;">' +
            '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"width="25px"height="25px"><path d="M421.45 285.195L376 239.746V212c0-6.627 5.373-12 12-12h24c6.627 0 12 5.373 12 12v44c0 9.957-.881 19.71-2.55 29.195zM352 96c0-53.019-42.981-96-96-96-32.574 0-61.354 16.227-78.71 41.035L352 215.746V96zm152.971 363.716L52.284 7.029c-9.373-9.373-24.569-9.373-33.941 0L7.029 18.343c-9.372 9.373-9.372 24.568 0 33.941L160 205.254v49.577c0 53.089 43.436 97.452 96.524 97.167 14.626-.078 28.471-3.44 40.854-9.366l17.746 17.746c-17.529 9.971-37.794 15.666-59.372 15.622C189.355 375.864 136 321.053 136 254.656V212c0-6.627-5.373-12-12-12h-24c-6.627 0-12 5.373-12 12v44c0 84.488 62.693 154.597 144 166.278V468h-68c-6.627 0-12 5.373-12 12v20c0 6.627 5.373 12 12 12h184c6.627 0 12-5.373 12-12v-20c0-6.627-5.373-12-12-12h-68v-45.722c25.625-3.682 49.396-13.172 69.942-27.083L459.717 504.97c9.373 9.373 24.569 9.373 33.941 0l11.313-11.313c9.372-9.373 9.372-24.568 0-33.941z"fill="#fff"/></svg>' +
            '</button>' +
            '<button id="stopSession" style="border-radius: 100%; width: 50px;height: 50px;background-color:rgb(0, 25, 58);margin-left:2%;opacity: 0.5;">' +
            '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 512"width="25px"height="25px"><path d="M268.2 381.4l-49.6-60.6c-6.8-8.3-18.2-11.1-28-6.9l-112 48c-10.7 4.6-16.5 16.1-13.9 27.5l24 104c2.5 10.8 12.1 18.6 23.4 18.6 100.7 0 193.7-32.4 269.7-86.9l-80-61.8c-10.9 6.5-22.1 12.7-33.6 18.1zm365.6 76.7L475.1 335.5C537.9 256.4 576 156.9 576 48c0-11.2-7.7-20.9-18.6-23.4l-104-24c-11.3-2.6-22.9 3.3-27.5 13.9l-48 112c-4.2 9.8-1.4 21.3 6.9 28l60.6 49.6c-12.2 26.1-27.9 50.3-46 72.8L45.5 3.4C38.5-2 28.5-.8 23 6.2L3.4 31.4c-5.4 7-4.2 17 2.8 22.4l588.4 454.7c7 5.4 17 4.2 22.5-2.8l19.6-25.3c5.4-6.8 4.1-16.9-2.9-22.3z"fill="#ff0000"/></svg>' +
            '</button>'
    );
    $videoControls.hide();


    var widgetConf = null
    var client = null;
    window.client = client;

    /**
     * run routine function after get name and service
     */
    $submit.on('click', function() {
        if ($customerName.val() && $serviceCode.val() && $serverUrl.val()) {
            customerName = $customerName.val();
            service = $serviceCode.val();
            widgetConf = createConfig();
            $info.show();
            $info.append('Customer name: ' + customerName + '\n');
            $info.append('Service: ' + service + '\n');
            routine(customerName, service);
            $settings.hide();
        } else {
            alert("Check the fields");
        }
    });

    /**
     * create new configuration object for widget
     */
    function createConfig() {
        return {
        server: {
                url: $serverUrl.val(),
            webrtc: {
                //configuration object of webrtc
                videoStreamInOffer: true,
                notifyAvailableMedia: true,
                mediaSignal: {
                    audioenabled: true,
                },
                mediaConfiguration: {
                    local: {
                        video: {
                            bandwidth: 1024,
                            constraints: {
                                width: 640,
                                height: 480,
                                frameRate: 30,
                            },
                        },
                    },
                },
                trickleIcePolicy: "NotSupported", // NotSupported - FullTrickle - HalfTrickle
				iceGatherPolicy: ["srflx", "relay"],
            }
        },
        servicesConfiguration: [],
        customerDisplayName: null,
        customerId: null
    };
        }

    /**
     * widget routine
     */
    function routine(customerName, service) {
        /**
         * Services Configuration
         */
        widgetConf.servicesConfiguration = [{
                services: [{code: service}],
                type: 'VIDEO'
        }];

        /*
         * widget client creation and connection
         */
        client = new TeleniaWidget.Widget(widgetConf);

        /**
        * log change of connection
        */
        client.getConntectionEvent().subscribe(function(connectionEvent) {
            console.log(connectionEvent);
            $info.append(`Connection's state changed: ${connectionEvent}\n`);
            // if (connectionEvent.connected) {
            //     $info.append('connected\n');
            // } else {
            //     $info.append('not connected\n');
            // }
        });

        client.onLoadClientComplete(function() {
            // client.sendCustomerIdentifier('VIDEO', service);

            $debugOn.show();
            $devicesStatus.show();
            $connectionTest.show();
            $videoChannelSession.show();
            /** 
             * AttachWebrtc to client
             */
            $info.append('Attach WebRTC Manager on client');
            client.attachWebrtcManager(widgetConf.server.webrtc);

            /**
             * monitor of service status for video channel
             */
            client.getServiceStatusForChannel(service, 'VIDEO').subscribe(function(statusForChannel) {
                if (statusForChannel.serviceConfiguration === 'NOT_FOUND') {
                    $info.append('Service ' + statusForChannel.service + ' not found on TVox\n');
                } else {
                    if (statusForChannel.service && statusForChannel.channelId && statusForChannel.status) {
                        $info.append(statusForChannel.service + ' channelConfiguration for ' + statusForChannel.channelId + ' channel: ' + statusForChannel.channelConfiguration + '\n');
                        $info.append(statusForChannel.service + ' serviceConfiguration for ' + statusForChannel.channelId + ' channel: ' + statusForChannel.serviceConfiguration + '\n');
                        $info.append(statusForChannel.service + ' status for ' + statusForChannel.channelId + ' channel: ' + statusForChannel.status + '\n');
                    } else {
                        $info.append('Error on get service status for ' + statusForChannel.service + '\n');
                    }
                }
                
            });
        });
        window.client = client;
    }

    /**
     * method invoked by video button in the widget - create video channel session
     */
    function videoChannelSession() {
        $info.append('New video channel session\n');
        /**
         * start monitoring session notify for QUEUE messages and connection stats
         */
        monitor = client.videoChannelSessionMonitor().subscribe(function(result) {
            console.log('videoChannelSessionMonitor - notify');
            console.log(result);
            if (result.state) {
                $info.append('***Video channel session notify***\n   state: ' + result.state + '\n');
                if (result.state == 'IDLE') {
                    currentVideoSessionId = null;
                    $videoLay.hide();
                    $videoControls.hide();
                    $videoChannelSession.show();
                    monitor.unsubscribe();
                }
            }
            if (result.step && result.step.waitingMessage) {
                //message about waiting queue
                $info.append('***STEP***\n   ' + result.step.waitingMessage + '\n');
            }
        });

        /**
         * new video session
         */
        client.videoChannelSessionNew(service, customerName).then(function(sessionId) {
                $videoLay.show();
                $videoControls.show();
                console.log('videoChannelSessionNew - response');
                console.log(sessionId);
                currentVideoSessionId = sessionId;
                client.getWebrtc().setVideoContainer(currentVideoSessionId, $videoLay[0]);
                $info.append('Video session id: ' + currentVideoSessionId + '\n');
            });
    }

    /**
     * Icon and button in the video layout to manage drop button
     */
    var $stopSession = $('#stopSession');

    $stopSession.on('click', function() {
        if (currentVideoSessionId) {
            client
                .videoChannelSessionClose(currentVideoSessionId)
                .then(function(result) {
                    console.log('multiChannelSessionClose - response');
                    console.log(result);
                })
                .catch(function(err) {
                    let error = WebApi.ErrorResolver.multiChannelSessionClose(err);
                    console.log('multiChannelSessionClose - error');
                    console.log(error);
                });
            console.log('multiChannelSessionClose - request');
        }
    });

    /**
     * Icon and button in the video layout to manage the video input
     */
    var $togglevideo = $('#circle-video');

    $togglevideo.on('click', function() {
        client.client.webrtc.toggleVideoMute(currentVideoSessionId);
        if (!videoCamera) {
            $togglevideo.html(
                '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 512"width="25px"height="25px"><path d="M633.8 458.1l-55-42.5c15.4-1.4 29.2-13.7 29.2-31.1v-257c0-25.5-29.1-40.4-50.4-25.8L448 177.3v137.2l-32-24.7v-178c0-26.4-21.4-47.8-47.8-47.8H123.9L45.5 3.4C38.5-2 28.5-.8 23 6.2L3.4 31.4c-5.4 7-4.2 17 2.8 22.4L42.7 82 416 370.6l178.5 138c7 5.4 17 4.2 22.5-2.8l19.6-25.3c5.5-6.9 4.2-17-2.8-22.4zM32 400.2c0 26.4 21.4 47.8 47.8 47.8h288.4c11.2 0 21.4-4 29.6-10.5L32 154.7v245.5z"fill="#fff"/></svg>'
            );
            videoCamera = true;
        } else {
            $togglevideo.html(
                '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512"width="25px"height="25px"><path d="M336.2 64H47.8C21.4 64 0 85.4 0 111.8v288.4C0 426.6 21.4 448 47.8 448h288.4c26.4 0 47.8-21.4 47.8-47.8V111.8c0-26.4-21.4-47.8-47.8-47.8zm189.4 37.7L416 177.3v157.4l109.6 75.5c21.2 14.6 50.4-.3 50.4-25.8V127.5c0-25.4-29.1-40.4-50.4-25.8z"fill="#fff"/></svg>'
            );
            videoCamera = false;
        }
    });

    /**
     * Icon and button in the video layout to manage the audio input
     */
    var $toggleaudio = $('#circle-audio');

    $toggleaudio.on('click', function() {
        client.client.webrtc.toggleAudioMute(currentVideoSessionId);
        if (!microphone) {
            $toggleaudio.html(
                '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"width="25px"height="25px"><path d="M421.45 285.195L376 239.746V212c0-6.627 5.373-12 12-12h24c6.627 0 12 5.373 12 12v44c0 9.957-.881 19.71-2.55 29.195zM352 96c0-53.019-42.981-96-96-96-32.574 0-61.354 16.227-78.71 41.035L352 215.746V96zm152.971 363.716L52.284 7.029c-9.373-9.373-24.569-9.373-33.941 0L7.029 18.343c-9.372 9.373-9.372 24.568 0 33.941L160 205.254v49.577c0 53.089 43.436 97.452 96.524 97.167 14.626-.078 28.471-3.44 40.854-9.366l17.746 17.746c-17.529 9.971-37.794 15.666-59.372 15.622C189.355 375.864 136 321.053 136 254.656V212c0-6.627-5.373-12-12-12h-24c-6.627 0-12 5.373-12 12v44c0 84.488 62.693 154.597 144 166.278V468h-68c-6.627 0-12 5.373-12 12v20c0 6.627 5.373 12 12 12h184c6.627 0 12-5.373 12-12v-20c0-6.627-5.373-12-12-12h-68v-45.722c25.625-3.682 49.396-13.172 69.942-27.083L459.717 504.97c9.373 9.373 24.569 9.373 33.941 0l11.313-11.313c9.372-9.373 9.372-24.568 0-33.941z"fill="#fff"/></svg>'
            );
            microphone = true;
        } else {
            $toggleaudio.html(
                '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 384 512"width="25px"height="25px" ><path d="M96 256V96c0-53.019 42.981-96 96-96s96 42.981 96 96v160c0 53.019-42.981 96-96 96s-96-42.981-96-96zm252-56h-24c-6.627 0-12 5.373-12 12v42.68c0 66.217-53.082 120.938-119.298 121.318C126.213 376.38 72 322.402 72 256v-44c0-6.627-5.373-12-12-12H36c-6.627 0-12 5.373-12 12v44c0 84.488 62.693 154.597 144 166.278V468h-68c-6.627 0-12 5.373-12 12v20c0 6.627 5.373 12 12 12h184c6.627 0 12-5.373 12-12v-20c0-6.627-5.373-12-12-12h-68v-45.722c81.307-11.681 144-81.79 144-166.278v-44c0-6.627-5.373-12-12-12z" fill="#fff"/></svg>'
            );
            microphone = false;
        }
    });

    /**
     * disconnect before close browser
     */
    window.addEventListener('beforeunload', function(event) {
        if (client) {
            client.transport.disconnect();
        }
    });

    $debugOn.on('click', function() {
        client.enableDebug();
        $info.append('*** Library debug enabled ***\n');
        $debugOn.hide();
        $debugOff.show();
    });

    $debugOff.on('click', function() {
        client.disableDebug();
        $info.append('*** Library debug disabled ***\n');
        $debugOn.show();
        $debugOff.hide();
    });

    $devicesStatus.on('click', function() {
        client.getLocalMediaAvailable().then((mediaDeviceEnabled) => {
            $info.append(`Devices enabled: ${JSON.stringify(mediaDeviceEnabled)}\n`);
        });
    });

    /** 
     * Test webrtc connection
     */
    $connectionTest.on("click", function() {
        $connectionTest.hide();
        client.echoTestertSessionNew(true, true).subscribe(function(testResult) {
            $info.append(`Connection test: ${JSON.stringify(testResult)}\n`);
            if (testResult.state === "SUCCESS") {
                //Test ok
                $connectionTest.show()
            } else if (testResult.state === "FAILED") {
                //test ko
                $connectionTest.show()
            }
        });
    });

    $videoChannelSession.on("click", function() {
        $videoChannelSession.hide();
        videoChannelSession();
    });
});