
/** moe-video enabler component **/

(function() {

    // state
    let moeOTSession = false;
    let moePublisher = false;
    let moeVideoElement = false;
    let moeArchiveID = false;

    // initialize elements, events
    function init(_container = false) {

        $('[moe-video-progress]').remove();
        $('<div/>')
            .attr('moe-video-progress', 1)
            .append('<img src="/img/loading.svg">')
            .appendTo('body');

        _container = $(_container || 'body');
        _container
            .find('[moe-video]:not([moe-initialized])')
                .each(function() {

                    // assign a unique id
                    let moeID = Math.ceil(Math.random() * 1000000);
                    $(this).attr('moe-id', moeID);

                    // if there's already a video, show it
                    let videoUrl = $(this).attr('moe-video-url');
                    if(!!videoUrl) {
                        $('<video/>')
                            .addClass('d-block mt-2 mb-3')
                            .attr({
                                'moe-answer-video': 1,
                                'controls': 1,
                                'src': videoUrl
                            })
                            .appendTo(this);
                    }

                    var buttonsDiv = $('<div class="d-flex flex-wrap" />').appendTo(this);

                    // record button
                    $('<button type="button" />')
                        .addClass('btn btn-sm btn-outline-info px-4 py-2 text-nowrap me-3 mb-2')
                        .attr('moe-show-popup', 1)
                        .html('<i class="fa fa-video me-2"></i>Record Answer')
                        .appendTo(buttonsDiv);

                    // upload button
                    $('<form enctype="multipart/form-data" ' +
                        'method="post" ' +
                        'class="d-inline-block mb-2" ' +
                        'action="/upload-video"/>')
                        .append('<input type="hidden" name="_token" value="' + $(this).attr('moe-csrf') + '">')
                        .append('<input type="hidden" name="question_key" value="' + $(this).attr('moe-question-key') + '" />')
                        .append(
                            $('<button type="button" />')
                                .addClass('btn btn-sm btn-outline-default border border-dark px-4 py-2 text-nowrap file')
                                .html('<i class="fa fa-upload me-2"></i>' +
                                    'Upload Video' +
                                    '<input type="file" class="input-file" name="hcp_intro" accept="video/*;capture=camcorder">')
                        )
                        .appendTo(buttonsDiv);

                    // mark as initialized
                    $(this).attr('moe-initialized', 1);

                });

        // bind events
        $(document).off('click.moe-show-popup', '[moe-video] [moe-show-popup]')
        $(document).on('click.moe-show-popup', '[moe-video] [moe-show-popup]', function() {
            initVideoPopup();
            moeVideoElement = $(this).closest('[moe-video]');
            $('[moe-video-backdrop]')
                .css('display', 'flex')
                .find('.card-title').first().text(moeVideoElement.find('p').first().text());
            initCamera(moeVideoElement);
        });

        $(document).off('click.moe-start-recording', '[moe-video-backdrop] [moe-start-recording]')
        $(document).on('click.moe-start-recording', '[moe-video-backdrop] [moe-start-recording]', function() {
            startWait();
            $('[moe-video-player]')
                .attr('src', '')
                .removeClass('d-block')
                .addClass('d-none');
            $('[moe-video-canvas]')
                .removeClass('d-none')
                .addClass('d-block');
            $.post('/start/' + moeVideoElement.attr('moe-ot-session-id'));
        });

        $(document).off('click.moe-stop-recording', '[moe-video-backdrop] [moe-stop-recording]')
        $(document).on('click.moe-stop-recording', '[moe-video-backdrop] [moe-stop-recording]', function() {
            startWait();
            $.post('stop/' +  moeArchiveID).complete(function () {
                $.ajax('/archive/'+ moeArchiveID, {
                    success: function (data) { // success callback function
                        stopWait();
                        $('[moe-video-player]')
                            .attr('src', data.video)
                            .removeClass('d-none')
                            .addClass('d-block');
                        $('[moe-video-canvas]')
                            .removeClass('d-block')
                            .addClass('d-none');
                        $('[moe-start-recording]').show();
                        $('[moe-stop-recording]').hide();
                        $('[moe-play-recording]').show();
                        $('[moe-restart-recording]').hide();
                        $('[moe-submit-recording]').show();
                        $('[moe-close-popup]').show();
                    }
                });
            });
        });

        $(document).off('click.moe-play-recording', '[moe-video-backdrop] [moe-play-recording]')
        $(document).on('click.moe-play-recording', '[moe-video-backdrop] [moe-play-recording]', function() {
            $('[moe-video-player]')[0].play();
        });

        $(document).off('click.moe-submit-recording', '[moe-video-backdrop] [moe-submit-recording]')
        $(document).on('click.moe-submit-recording', '[moe-video-backdrop] [moe-submit-recording]', function() {
            startWait();
            $.post('/save-archive', {
                archiveID: moeArchiveID,
                question_key: moeVideoElement.attr('moe-question-key')
            }, function(_data) {
                if(!!moeOTSession) {
                    moeOTSession.disconnect();
                    moeOTSession = false;
                    moePublisher = false;
                }
                // $('[moe-video-backdrop]').css('display', 'none');
                window.location.reload();
            }, 'json');
        });

        $(document).off('click.moe-close-popup', '[moe-video-backdrop] [moe-close-popup]')
        $(document).on('click.moe-close-popup', '[moe-video-backdrop] [moe-close-popup]', function() {
            if(!!moeOTSession) {
                moeOTSession.disconnect();
                moeOTSession = false;
                moePublisher = false;
            }
            $('[moe-video-backdrop]').css('display', 'none');
        });

        $(document).off('change.input-file', '[moe-video] .input-file')
        $(document).on('change.input-file', '[moe-video] .input-file', function() {
            $(this).closest('form').submit();
        });
    }

    function initVideoPopup() {
        $('[moe-video-backdrop]').remove();
        $('<div moe-video-backdrop>' +
            '<div class="card">' +
                '<div class="card-header">' +
                    '<div class="card-title text-secondary"></div>' +
                '</div>' +
                '<div class="card-body">' +
                    '<div class="access-information">' +
                        '<p>Setting up camera and microphone access...</p>' +
                        '<p class="click-allow d-none">Click "Allow" to allow hardware access and begin the recording</p>' +
                        '<div class="denied d-none">' +
                            '<p class="text-danger"><b>It appears we do not have access to your input hardware.</b></p>' +
                            '<p class="font-weight-normal">Please allow access to your hardware by clicking the ' +
                                '<img class="border border-dark" src="/img/denied.png" alt=""> icon ' +
                                'towards the far right of the browser address bar. <b>Once done, please click <a href="">here</a> to refresh the page and retry.</b></p>' +
                        '</div>' +
                    '</div>' +
                    '<div moe-video-canvas class="d-none"></div>' +
                    '<video moe-video-player class="d-none" controls><source src="" type="video/mp4"></video>' +
                '</div>' +
                '<div class="card-footer">' +
                    '<div class="d-flex align-items-center justify-content-center">' +
                        '<button type="button" class="btn btn-danger btn-sm me-3" moe-start-recording>' +
                            '<i class="fa fa-video me-2"></i>Record' +
                        '</button>' +
                        '<button type="button" class="btn btn-danger btn-sm me-3" moe-stop-recording>' +
                            '<i class="fa fa-stop me-2"></i>Stop' +
                        '</button>' +
                        '<button type="button" class="btn btn-info btn-sm me-3" moe-play-recording>' +
                            '<i class="fa fa-play me-2"></i>Play' +
                        '</button>' +
                        '<button type="button" class="btn btn-info btn-sm me-3" moe-restart-recording>' +
                            '<i class="fa fa-play me-2"></i>Play' +
                        '</button>' +
                        '<button type="button" class="btn btn-success btn-sm me-3" moe-submit-recording>' +
                            '<i class="fa fa-check me-2"></i>Submit' +
                        '</button>' +
                        '<button type="button" class="btn btn-default bg-light border border-default btn-sm me-3" moe-close-popup>' +
                            '<i class="fa fa-times me-2"></i>Close' +
                        '</button>' +
                        '<span moe-wait>Please wait...</span>' +
                    '</div>' +
                '</div>' +
            '</div>' +
        '</div>').appendTo('body');
    }

    function startWait() {
        $('[moe-start-recording]').hide();
        $('[moe-stop-recording]').hide();
        $('[moe-play-recording]').hide();
        $('[moe-restart-recording]').hide();
        $('[moe-submit-recording]').hide();
        $('[moe-close-popup]').hide();
        $('[moe-wait]').show();
        $('[moe-video-progress]').removeClass('d-none').addClass('d-flex');
    }

    function stopWait() {
        $('[moe-wait]').hide();
        $('[moe-video-progress]').removeClass('d-flex').addClass('d-none');
    }

    // init ot, publisher and show cam feed
    function initCamera(_moeVideoElement) {

        startWait();

        // cleanup
        if(!!moeOTSession) {
            moeOTSession.disconnect();
            moeOTSession = false;
            moePublisher = false;
        }

        // create session (using sessionID given by the server)
        moeOTSession = OT.initSession(
            _moeVideoElement.attr('moe-ot-api-key'),
            _moeVideoElement.attr('moe-ot-session-id')
        );

        // init publisher
        moePublisher = OT.initPublisher(
            $('[moe-video-canvas]').first()[0],
            {
                //videoSource: 'screen', // comment out in prod
                width: 540
            }
        );

        // publisher events
        moePublisher.on({
            accessAllowed: function (event) {
                // The user has granted access to the camera and mic.
                console.log('ALIX: accessAllowed');
                $('.access-information').removeClass('d-block').addClass('d-none');
                $('[moe-video-canvas]').removeClass('d-none').addClass('d-block');
                stopWait()
            },
            accessDenied: function accessDeniedHandler(event) {
                // The user has denied access to the camera and mic.
                console.log('ALIX: accessDenied');
                $('.click-allow').addClass('d-none');
                $('.denied').removeClass('d-none');
                stopWait()
            },
            accessDialogOpened: function (event) {
                // The Allow/Deny dialog box is opened.
                console.log('ALIX: accessDialogOpened');
                $('.click-allow').removeClass('d-none');
                stopWait()
            },
            accessDialogClosed: function (event) {
                // The Allow/Deny dialog box is closed.
                console.log('ALIX: accessDialogClosed');
                stopWait()
            }
        });

        // OT events
        moeOTSession.connect(_moeVideoElement.attr('moe-ot-client-token'), function(error) {
            if (error) {
                console.error('Failed to connect', error);
            } else {
                moeOTSession.publish(moePublisher, function(error) {
                    if (error) {
                        console.error('Failed to publish', error);
                    }
                    else {
                        stopWait();
                        $('[moe-start-recording]').show();
                        $('[moe-stop-recording]').hide();
                        $('[moe-play-recording]').hide();
                        $('[moe-restart-recording]').hide();
                        $('[moe-submit-recording]').hide();
                        $('[moe-close-popup]').show();
                    }
                });
            }
        });
        moeOTSession.on('archiveStarted', function(event) {
            stopWait();
            moeArchiveID = event.id;
            $('[moe-start-recording]').hide();
            $('[moe-stop-recording]').show();
            $('[moe-play-recording]').hide();
            $('[moe-restart-recording]').hide();
            $('[moe-submit-recording]').hide();
            $('[moe-close-popup]').hide();
        });
        moeOTSession.on('archiveStopped', function() {
            // moeArchiveID = false;
            // stopWait();
            // $('[moe-start-recording]').show();
            // $('[moe-stop-recording]').hide();
            // $('[moe-play-recording]').hide();
            // $('[moe-restart-recording]').hide();
            // $('[moe-submit-recording]').hide();
            // $('[moe-close-popup]').show();
        });
    }

    $(document).ready(function() {
        init();
    });
})();
