
/** moe-video enabler component **/

(function() {

    function hasResponseError(_data) {
        let msg = 'Unknown error!';
        if (_data) {
            if (_data.success) return false;
            else if (_data.message) msg = _data.message;
        }
        toastr.error(msg);
        return true;
    }

    // state
    let moeOTSession = false;
    let moePublisher = false;
    let moeVideoElement = false;
    let moeArchiveID = false;
    let uploadOrRecord = 'record';

    // 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);


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

                // record button
                $('<button type="button" />')
                    .addClass('btn btn-info ' + ($(this).attr('custom-handler') ? '' : 'btn-sm ml-2'))
                    .attr('moe-show-popup', 1)
                    .html($(this).attr('custom-handler') ? 'Upload or Record Video' : '<i class="fa fa-video"></i>')
                    .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]');
            let title = moeVideoElement.find('p').first().text();
            if(!title) {
                title = moeVideoElement.attr('data-title');
            }
            $('[moe-video-backdrop]')
                .css('display', 'flex')
                .find('.card-title').first().text(title);

        });

        $(document).off('change.moe-video-file', '[moe-video-file]')
        $(document).on('change.moe-video-file', '[moe-video-file]', function() {

            // check if video
            let file = this.files[0];
            if(file.type !== 'video/mp4' && file.type !== 'video/mpeg' && file.type !== 'video/webm') {
                toastr.error('Invalid video file!');
                return false;
            }
            let blobURL = URL.createObjectURL(file);

            $('[moe-video-player]')
                .attr('src', blobURL)
                .removeClass('d-none')
                .addClass('d-block');
            $('.upload-or-record')
                .removeClass('d-block')
                .addClass('d-none');
            $('[moe-play-recording]').show();
            $('[moe-submit-recording]').show();
            $('[moe-close-popup]').show();

            uploadOrRecord = 'upload';

            return false;
        });

        $(document).off('click.moe-choose-record', '[moe-choose-record]')
        $(document).on('click.moe-choose-record', '[moe-choose-record]', function() {
            initCamera(moeVideoElement);
            uploadOrRecord = 'record';
            return false;
        });

        $(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).done(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() {

            //TODO: remove closest('body')
            var toProUid = $('[moe-submit-recording]').closest('body').find('[to-pro-uid]').attr('to-pro-uid');
            var regardingCompanyUid = $('[moe-submit-recording]').closest('body').find('[regarding-company-uid]').attr('regarding-company-uid');
            var regardingClientUid = $('[moe-submit-recording]').closest('body').find('[regarding-client-uid]').attr('regarding-client-uid');
            var customHandler = $('[moe-submit-recording]').closest('body').find('[custom-handler]').attr('custom-handler');
            var proUid = $('[moe-submit-recording]').closest('body').find('[pro-uid]').attr('pro-uid');

            if(uploadOrRecord === 'upload') {

                startWait();

                let formData = new FormData();
                    formData.set('regardingCompanyUid', regardingCompanyUid);
                    formData.set('regardingClientUid', regardingClientUid);
                    formData.set('contentText', '');
                    let videoInput = $('[moe-submit-recording]').closest('body').find('[moe-video-file]').first()[0];
                    formData.append('messageVideo', videoInput.files[0]);

                    $.ajax('/api/internalMessage/create', {
                        dataType: 'json',
                        data: formData,
                        processData: false,
                        contentType: false,
                        type: 'POST',
                    }).done(function (_data) {
                        if(!hasResponseError(_data)) {
                            window.top.location.reload();
                        }
                    });
                    return false;

            }
            else if(uploadOrRecord === 'record') {
                startWait();

                $.post('/save-archive', {
                    archiveID: moeArchiveID,
                    toProUid: toProUid,
                    regardingCompanyUid: regardingCompanyUid,
                    regardingClientUid: regardingClientUid,
                    contentText: '',
                }, function(_data) {
                    stopWait();
                    if(!!moeOTSession) {
                        moeOTSession.disconnect();
                        moeOTSession = false;
                        moePublisher = false;
                    }
                    // $('[moe-video-backdrop]').css('display', 'none');
                    window.top.location.reload();
                }, 'json');
            }

            return false;
        });

        $(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 mcp-theme-1">' +
            '<div class="card-header py-2 d-flex align-items-baseline">' +
            '<div class="card-title text-left flex-grow-1"></div>' +
            '<a href="#" class="text-secondary ml-auto" moe-close-popup><i class="fa fa-times-circle"></i></a>' +
            '</div>' +
            '<div class="card-body">' +
            '<div class="upload-or-record">' +
            '<div class="d-flex align-items-center justify-content-center">' +
            '<button type="button" class="btn btn-primary font-weight-bold mr-3 position-relative overflow-hidden" moe-choose-upload>' +
            '<i class="fa fa-file-upload mr-2"></i>Upload' +
            '<input type="file" moe-video-file class="position-absolute opacity-0x" style="bottom: 0; right: 0">' +
            '</button>' +
            '<button type="button" class="btn btn-primary font-weight-bold" moe-choose-record>' +
            '<i class="fa fa-video mr-2"></i>Record' +
            '</button>' +
            '</div>' +
            '</div>' +
            '<div class="access-information d-none">' +
            '<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 mr-3" moe-start-recording style="display: none">' +
            '<i class="fa fa-video mr-2"></i>Record' +
            '</button>' +
            '<button type="button" class="btn btn-danger btn-sm mr-3" moe-stop-recording style="display: none">' +
            '<i class="fa fa-stop mr-2"></i>Stop' +
            '</button>' +
            '<button type="button" class="btn btn-info btn-sm mr-3" moe-play-recording style="display: none">' +
            '<i class="fa fa-play mr-2"></i>Play' +
            '</button>' +
            '<button type="button" class="btn btn-info btn-sm mr-3" moe-restart-recording style="display: none">' +
            '<i class="fa fa-play mr-2"></i>Play' +
            '</button>' +
            '<button type="button" class="btn btn-success btn-sm mr-3" moe-submit-recording style="display: none">' +
            '<i class="fa fa-check mr-2"></i>Submit' +
            '</button>' +
            '<button type="button" class="btn btn-default bg-light border border-default btn-sm mr-3" moe-close-popup style="display: none">' +
            '<i class="fa fa-times mr-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();

        $('.upload-or-record').removeClass('d-block').addClass('d-none');
        $('.access-information').removeClass('d-none').addClass('d-block');

        // 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');
                $('[moe-start-recording]').show();
                $('[moe-close-popup]').show();
                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();
    });
})();
