/**
 * @license Licensed under the Apache License, Version 2.0 (the "License"):
 *          http://www.apache.org/licenses/LICENSE-2.0
 *
 * @fileoverview JavaScript to configure front end design for Ardublockly app.
 */
'use strict';

/** Create a namespace for the application. */
var Ardublockly = Ardublockly || {};


/** Initialises all the design related JavaScript. */
Ardublockly.designJsInit = function () {
    Ardublockly.materializeJsInit();
    Ardublockly.sketchNameSizeEffect();
    Ardublockly.sketchNameSet();
    // Ardublockly.cloudSketchNameSizeEffect();
    // Ardublockly.cloudSketchNameSet();

};

/**
 * Initialises all required components from materialize framework.
 * The be executed on document ready.
 */
Ardublockly.materializeJsInit = function () {
    // Navigation bar
    $('.button-collapse').sideNav({
        menuWidth: 240,
        activationWidth: 70,
        edge: 'left'
    });

    //   // Serial bar
    // $('.button-collapse-right').sideNav({
    //     menuWidth: 550,
    //     activationWidth: 70,
    //     edge: 'right',
    //     onCloseStart: function(){

    //     }
    // });
    $('.modal').modal({
        dismissible: true,
        opacity: .5,
        in_duration: 200,
        out_duration: 250
    });
    // Drop down menus
    $('.dropdown-button').dropdown({ hover: false });
    // Overlay content panels using modals (android dialogs)

    $("ul.tabs").tabs({
        swipeable: true,
        responsiveThreshold: 220
    })

    $("#app_center_modal").modal({
        ready: () => {

            $(".tab:nth-child(1)>a").click()
        }
    })


    $('#setting_teacher').modal({
        ready: () => {
        },
    })
    //Teachable Machine modal 
    $('#Teachable_Machine').modal({
        ready: () => {
            $('#setting_teacher').modal("close")
            if (platform.name === "Chrome" || platform.name === "Firefox") {
                console.log('chrome or Firefox')
            } else {
                Ardublockly.alertMessage(
                    Ardublockly.getLocalStr('unsupportWebcamTitle'),
                    Ardublockly.getLocalStr('unsupportWebcamBody'),
                    false);
                $('#Teachable_Machine').modal('close')
                return;
            }

            if (window.location.href.split("://")[0] === "http") {
                Ardublockly.customAlertMessage(
                    Ardublockly.getLocalStr('requestWebcamTitle'),
                    Ardublockly.getLocalStr('requestWebcamBody'),
                    Ardublockly.getLocalStr('goHttps'),
                    () => {
                        window.location.href = "https://" + window.location.href.split("://")[1]
                    });
                $('#Teachable_Machine').modal('close')
                return;
            }

            if (!CCB.userState) {
                document.getElementById('teachable_modal').style.display = 'none'
            }
            CCB.UserInfo = CCB.UserInfo || {}
            let lang = 'en';
            document.location.search.substring(1).split('&').forEach((item) => {
                if (item.split('=')[0] == 'lang') {
                    lang = item.split('=')[1];
                }
            });
            CCB.UserInfo.url = lang;
            CCB.UserInfo.boards = CCB.boards[0];
            $("#TM_id").css("height", $("#Teachable_Machine")[0].offsetHeight)
            // document.getElementById("TM_id").contentWindow.postMessage("startCam", "*")
            appendTMIframe("TM_iframe", function () { document.getElementById("TM_id").contentWindow.postMessage(CCB.UserInfo, "*"); }, "//ai-demos.cocorobo.cn/teachable-machine-2/public/");
            let loading = document.getElementById('TM_id');
            loading.onload = () => {
                document.getElementById("TM_id").contentWindow.postMessage(CCB.UserInfo, "*")
                // window.addEventListener('message', function (e) {
                //     if (e.data === 'none') {
                //     }
                // })
                setTimeout(() => {
                    document.getElementById('teachable_modal').style.display = 'none'
                }, 1000)
            }

            // CCB.socket && CCB.socket.emit('command', {
            //     cmd: 'open',
            //     option: { port: $('#ports').val(), baud: $('#serial_baud').val() }
            // });
            window.addEventListener('message', function (e) {
                let data = '';
                if (document.getElementById('TM_id_posenet') && CCB.isOpen && e.data !== "close") {
                    for (const key in e.data) {
                        if (e.data[key] === "yes") {
                            data = key
                        }
                    }
                    data = data.slice(6) === "A" ? "green" : data.slice(6) === "B" ? "purple" : "orange"
                    // socket 发送数据
                    CCB.socket && CCB.socket.emit('command', {
                        cmd: 'send',
                        option: { msg: `SOF|${data}|`, postfix: "blc" }
                    })
                }
            }, false);
        },
        // 点击 遮罩层 关闭弹框
        complete: () => {
            document.getElementById("TM_id").contentWindow.postMessage("stopCam", "*")
            let obj = document.getElementById('TM_id');
            if (obj) {
                obj.parentNode.removeChild(obj)
                document.getElementById('teachable_modal').style.display = 'block'
                // socket 关闭
                CCB.socket && CCB.socket.emit('command', { cmd: 'close' });
            }
        }
    })

    $('#setting_teacher_ponsenet').modal({
        ready: () => {
        },
    })
    //Teachable Machine modal 
    $('#Teachable_Machine_ponsenet').modal({
        ready: () => {
            $('#setting_teacher_ponsenet').modal("close")
            if (platform.name === "Chrome" || platform.name === "Firefox") {
                console.log('chrome or Firefox')
            } else {
                Ardublockly.alertMessage(
                    Ardublockly.getLocalStr('unsupportWebcamTitle'),
                    Ardublockly.getLocalStr('unsupportWebcamBody'),
                    false);
                $('#Teachable_Machine_ponsenet').modal('close')
                return;
            }

            if (window.location.href.split("://")[0] === "http") {
                Ardublockly.customAlertMessage(
                    Ardublockly.getLocalStr('requestWebcamTitle'),
                    Ardublockly.getLocalStr('requestWebcamBody'),
                    Ardublockly.getLocalStr('goHttps'),
                    () => {
                        window.location.href = "https://" + window.location.href.split("://")[1]
                    });
                $('#Teachable_Machine_ponsenet').modal('close')
                return;
            }

            if (!CCB.userState) {
                document.getElementById('teachable_posenet_modal').style.display = 'none'
            }
            CCB.UserInfo = CCB.UserInfo || {}
            let lang = 'en';
            document.location.search.substring(1).split('&').forEach((item) => {
                if (item.split('=')[0] == 'lang') {
                    lang = item.split('=')[1];
                }
            });
            CCB.UserInfo.url = lang;
            CCB.UserInfo.boards = CCB.boards[0];
            $("#TM_posenet_id").css("height", $("#Teachable_Machine_ponsenet")[0].offsetHeight)
            // document.getElementById("TM_id").contentWindow.postMessage("startCam", "*")
            let url = "//ai-demos.cocorobo.cn/teachable-machine-pose-recognition-2/public/"
            appendTMPosenetIframe("TM_posenet_iframe", function () { document.getElementById("TM_posenet_id").contentWindow.postMessage(CCB.UserInfo, "*"); }, url);
            let loading = document.getElementById('TM_posenet_id');
            loading.onload = () => {
                document.getElementById("TM_posenet_id").contentWindow.postMessage(CCB.UserInfo, "*")
                // window.addEventListener('message', function (e) {
                //     if (e.data === 'none') {
                //     }
                // })
                setTimeout(() => {
                    document.getElementById('teachable_posenet_modal').style.display = 'none'
                }, 1000)
            }
            window.addEventListener('message', function (e) {
                if (document.getElementById('TM_posenet_id') && CCB.isOpen && e.data !== "close") {
                    let data = '';
                    for (const key in e.data.data) {
                        if (e.data.data[key] !== "no") {
                            data = e.data.data[key]
                        }
                    }
                    // data = data.slice(6) === "A" ? "green" : data.slice(6) === "B" ? "purple" : "orange"
                    // socket 发送数据
                    CCB.socket && CCB.socket.emit('command', {
                        cmd: 'send',
                        option: { msg: `SOF|${data}|${e.data.posenet ? e.data.posenet : ""}|`, postfix: "blc" }
                    })
                }
            }, false);
        },
        // 点击 遮罩层 关闭弹框
        complete: () => {
            let obj = document.getElementById('TM_posenet_id');
            if (obj) {
                document.getElementById("TM_posenet_id").contentWindow.postMessage("stopCam", "*")
                obj.parentNode.removeChild(obj)
                document.getElementById('teachable_posenet_modal').style.display = 'block'
                // socket 关闭
                CCB.socket && CCB.socket.emit('command', { cmd: 'close' });
            }
        }
    })

    $("#setting_webcam_capture_modal").modal({
        ready: () => {

        }
    })

    $('#webcam_capture_modal').modal({

        ready: () => {
            $('#setting_webcam_capture_modal').modal('close');
            if (window.location.href.split("://")[0] === "http") {
                Ardublockly.customAlertMessage(
                    Ardublockly.getLocalStr('requestWebcamTitle'),
                    Ardublockly.getLocalStr('requestWebcamBody'),
                    Ardublockly.getLocalStr('goHttps'),
                    () => {
                        window.location.href = "https://" + window.location.href.split("://")[1]
                    });
                $('#webcam_capture_modal').modal('close');
                return;
            }
            window.send = 'cloud';
            window.isSend = false;
            $('.translatable_disconnectBtn').css('display', 'none');
            $('.translatable_connectBtn').css({ "float": "right", 'margin-right': '5px', 'display': 'block' });
            $('.translatable_send_cloud').addClass('select_send_way_color');
            $('.translatable_send_module').removeClass('select_send_way_color');
            $('.send_cloud').css({ 'display': 'block', 'position': 'relative' });
            $('.send_module').css({ 'display': 'none', 'position': 'relative' });
            $('.port').text(CCB.boards[0])
            if (CCB.boards.length > 0 && CCB.userState) {
                $('.translatable_connectBtn').removeClass('disabled');
                //     CCB.socket && CCB.socket.emit('command', {
                //         cmd: 'open',
                //         option: { port: $('#ports').val(), baud: $('#serial_baud').val() }
                //     });
            }
        },
        complete: () => {
            document.getElementById('camera_switch').checked = false;
            Webcam.reset();
            CCB.socket && CCB.socket.emit('command', { cmd: 'close' });
        }
    })

    $("#setting_gesture_recog_modal").modal({
        ready: () => {

        }
    })

    $('#gesture_recog_modal').modal({

        ready: () => {
            $('#setting_gesture_recog_modal').modal('close');
            if (window.location.href.split("://")[0] === "http") {
                Ardublockly.customAlertMessage(
                    Ardublockly.getLocalStr('requestWebcamTitle'),
                    Ardublockly.getLocalStr('requestWebcamBody'),
                    Ardublockly.getLocalStr('goHttps'),
                    () => {
                        window.location.href = "https://" + window.location.href.split("://")[1]
                    });
                $('#gesture_recog_modal').modal('close');
                return;
            }

            window.send = 'cloud';
            window.isSend = false;
            $('.translatable_disconnectBtn').css('display', 'none');
            $('.translatable_connectBtn').css({ "float": "right", 'margin-right': '5px', 'display': 'block' });
            $('.translatable_send_cloud').addClass('select_send_way_color');
            $('.translatable_send_module').removeClass('select_send_way_color');
            $('.send_cloud').css({ 'display': 'block', 'position': 'relative' });
            $('.send_module').css({ 'display': 'none', 'position': 'relative' });
            $('.port').text(CCB.boards[0])
            if (CCB.boards.length > 0 && CCB.userState) {
                $('.translatable_connectBtn').removeClass('disabled');
                // CCB.socket && CCB.socket.emit('command', {
                //     cmd: 'open',
                //     option: { port: $('#ports').val(), baud: $('#serial_baud').val() }
                // });
            }
        },
        complete: () => {
            document.getElementById('gestureAnalyzeButton').innerHTML = CCB.str_group.gesture_recognition_button_analyze;
            document.getElementById('cloudRequestStatuss').innerHTML = '';
            document.getElementById('gestureResultAreaContent').innerHTML = CCB.str_group.gesture_recognition_button_result;
            document.getElementById('camera_switch_gesture').checked = false;
            Webcam.reset();
            $("#gestureAnalyzeButton").addClass("disabled");
            $('#webCameraGesture').removeClass("webCameraGestureCapturedStyling");
            CCB.socket && CCB.socket.emit('command', { cmd: 'close' });
        }
    })

    $("#setting_voice_input_modal").modal({
        ready: () => {

        }
    })


    $('#voice_input_modal').modal({
        ready: () => {
            $('#setting_voice_input_modal').modal('close');
            if (window.location.href.split("://")[0] === "http") {
                Ardublockly.customAlertMessage(
                    Ardublockly.getLocalStr('requestVoiceRecognitionTitle'),
                    Ardublockly.getLocalStr('requestVoiceRecognitionBody'),
                    Ardublockly.getLocalStr('goHttps'),
                    () => {
                        window.location.href = "https://" + window.location.href.split("://")[1]
                    });
                $('#voice_input_modal').modal('close');
                return;
            }

            window.send = 'cloud';
            window.isSend = false;
            $('.translatable_disconnectBtn').css('display', 'none');
            $('.translatable_connectBtn').css({ "float": "right", 'margin-right': '5px', 'display': 'block' });
            $('.translatable_send_cloud').addClass('select_send_way_color');
            $('.translatable_send_module').removeClass('select_send_way_color');
            $('.send_cloud').css({ 'display': 'block', 'position': 'relative' });
            $('.send_module').css({ 'display': 'none', 'position': 'relative' });
            $('.port').text(CCB.boards[0])
            if (CCB.boards.length > 0 && CCB.userState) {
                $('.translatable_connectBtn').removeClass('disabled');
                // CCB.socket && CCB.socket.emit('command', {
                //     cmd: 'open',
                //     option: { port: $('#ports').val(), baud: $('#serial_baud').val() }
                // });
            }
        },
        complete: () => {
            $('#speech_button').html(CCB.str_group.start_speech);
            CCB.socket && CCB.socket.emit('command', { cmd: 'close' });
        }
    })

    $('#real_time_voice_input_modal').modal({
        ready: () => {
            if (window.location.href.split("://")[0] === "http") {
                Ardublockly.customAlertMessage(
                    Ardublockly.getLocalStr('requestVoiceRecognitionTitle'),
                    Ardublockly.getLocalStr('requestVoiceRecognitionBody'),
                    Ardublockly.getLocalStr('goHttps'),
                    () => {
                        window.location.href = "https://" + window.location.href.split("://")[1]
                    });
                $('#real_time_voice_input_modal').modal('close');
                return;
            }
        },
    })



    $('#setting_objectRecog').modal({
        ready: () => {

        },
    })

    // 日志
    $('#change_log').modal({
        ready: () => {
            if (!document.getElementById('changLog').style.opacity == '1') {
                document.getElementById('changLog').contentWindow.location.reload();
            }
            setTimeout(() => {
                document.getElementById('changLog').style.opacity = '1'
                document.getElementById('changLog').contentWindow.document.getElementsByTagName('body')[0].setAttribute('class', 'ready close')
                document.getElementById('changLog').contentWindow.document.getElementsByClassName('sidebar-toggle')[0].style.visibility = "hidden";
                document.getElementById('changLog').contentWindow.document.getElementsByClassName('body-nav')[0].style.visibility = "hidden"
            }, 1000)
        }
    })

    $('#Object_recog_modal').modal({
        // 打开弹框
        ready: () => {
            $('#setting_objectRecog').modal("close")
            if (platform.name === "Chrome" || platform.name === "Firefox") {
                console.log('chrome or Firefox')
            } else {
                Ardublockly.alertMessage(
                    Ardublockly.getLocalStr('unsupportWebcamTitle'),
                    Ardublockly.getLocalStr('unsupportWebcamBody'),
                    false);
                $('#Object_recog_modal').modal('close')
                return;
            }
            if (window.location.href.split("://")[0] === "http") {
                Ardublockly.customAlertMessage(
                    Ardublockly.getLocalStr('requestWebcamTitle'),
                    Ardublockly.getLocalStr('requestWebcamBody'),
                    Ardublockly.getLocalStr('goHttps'),
                    () => {
                        window.location.href = "https://" + window.location.href.split("://")[1]
                    });
                $('#Object_recog_modal').modal('close');
                return;
            }
            if (!CCB.userState) {
                document.getElementById('object_modal').style.display = 'none'
            }
            CCB.UserInfo = CCB.UserInfo || {}

            let lang = 'en';
            document.location.search.substring(1).split('&').forEach((item) => {
                if (item.split('=')[0] == 'lang') {
                    lang = item.split('=')[1];
                }
            });
            CCB.UserInfo.boards = CCB.boards[0];
            $("#TM_id_object").css("height", $("#Object_recog_modal")[0].offsetHeight)
            CCB.UserInfo.state = "startCam"
            CCB.UserInfo.url = lang
            appendTMIframes("TM_iframe_object", function () { document.getElementById("TM_id_object").contentWindow.postMessage(CCB.UserInfo, "*"); }, "//ai-demos.cocorobo.cn/object-detection-2/");
            let loading = document.getElementById('TM_id_object');
            loading.onload = () => {
                document.getElementById("TM_id_object").contentWindow.postMessage(CCB.UserInfo, "*")
                setTimeout(() => {
                    document.getElementById('object_modal').style.display = 'none'
                }, 1000)
            }
            // CCB.socket && CCB.socket.emit('command', {
            //     cmd: 'open',
            //     option: { port: $('#ports').val(), baud: $('#serial_baud').val() }
            // });
            window.addEventListener('message', function (e) {
                console.log('data', e.data)
                if (document.getElementById('TM_id_posenet') && CCB.isOpen && e.data !== "close") {
                    let data = ''
                    e.data && e.data.slice(0, 8).map(x => {
                        data = data + x.class + '|'
                    })
                    // socket 发送数据
                    CCB.socket && CCB.socket.emit('command', {
                        cmd: 'send',
                        option: { msg: `SOF|${data}`, postfix: "blc" }
                    })
                }
            }, false);

        },
        // 关闭弹框
        complete: () => {
            let obj = document.getElementById('TM_id_object');
            if (obj) {
                obj.parentNode.removeChild(obj)
                document.getElementById('object_modal').style.display = 'block'
                CCB.socket && CCB.socket.emit('command', { cmd: 'close' });
            }
        }
    })

    // 姿态识别

    $('#setting_posenetRecog').modal({
        ready: () => {

        },
    })

    $('#Posent_recog_modal').modal({
        // 打开弹框
        ready: () => {
            $('#setting_posenetRecog').modal("close")
            if (platform.name === "Chrome" || platform.name === "Firefox") {
                console.log('chrome or Firefox')
            } else {
                Ardublockly.alertMessage(
                    Ardublockly.getLocalStr('unsupportWebcamTitle'),
                    Ardublockly.getLocalStr('unsupportWebcamBody'),
                    false);
                $('#Posent_recog_modal').modal('close')
                return;
            }
            if (window.location.href.split("://")[0] === "http") {
                Ardublockly.customAlertMessage(
                    Ardublockly.getLocalStr('requestWebcamTitle'),
                    Ardublockly.getLocalStr('requestWebcamBody'),
                    Ardublockly.getLocalStr('goHttps'),
                    () => {
                        window.location.href = "https://" + window.location.href.split("://")[1]
                    });
                $('#Posent_recog_modal').modal('close');
                return;
            }
            if (!CCB.userState) {
                document.getElementById('posenet_modal').style.display = 'none'
            }
            CCB.UserInfo = CCB.UserInfo || {}

            let lang = 'en';
            document.location.search.substring(1).split('&').forEach((item) => {
                if (item.split('=')[0] == 'lang') {
                    lang = item.split('=')[1];
                }
            });
            $("#TM_id_posenet").css("height", $("#Posent_recog_modal")[0].offsetHeight)
            CCB.UserInfo.state = "startCam";
            CCB.UserInfo.url = lang;
            CCB.UserInfo.boards = CCB.boards[0];
            appendTMIframePosenet("TM_iframe_posenet", function () { document.getElementById("TM_id_posenet").contentWindow.postMessage(CCB.UserInfo, "*"); }, "//ai-demos.cocorobo.cn/posenet-2/demos/dist/");
            let loading = document.getElementById('TM_id_posenet');
            loading.onload = () => {
                document.getElementById("TM_id_posenet").contentWindow.postMessage(CCB.UserInfo, "*")
                setTimeout(() => {
                    document.getElementById('posenet_modal').style.display = 'none'
                }, 1000)
            }
            // socket 连接
            CCB.socket && CCB.socket.emit('command', {
                cmd: 'open',
                option: { port: $('#ports').val(), baud: $('#serial_baud').val() }
            });
            window.addEventListener('message', function (e) {
                console.log("iframe data", e.data)
                // socket 发送数据
                if (document.getElementById('TM_id_posenet') && CCB.isOpen && e.data !== "close") {
                    CCB.socket && CCB.socket.emit('command', {
                        cmd: 'send',
                        option: { msg: `SOF|${e.data.posture}|`, postfix: "blc" }
                    })
                }

            }, false);

        },
        // 关闭弹框
        complete: () => {
            let obj = document.getElementById('TM_id_posenet');
            if (obj) {
                obj.parentNode.removeChild(obj)
                document.getElementById('posenet_modal').style.display = 'block'
                // socket 关闭
                CCB.socket && CCB.socket.emit('command', { cmd: 'close' });
            }
        }
    })


    // 机器人控制
    $('#controller').modal({
        ready: () => {
            // socket 连接
            if (CCB.boards.length > 0) {
                CCB.issend = true;
                CCB.socket && CCB.socket.emit('command', {
                    cmd: 'open',
                    option: { port: $('#ports').val(), baud: $('#serial_baud').val() }
                });
            }
        },
        complete: () => {
            CCB.socket && CCB.socket.emit('command', { cmd: 'close' });
            CCB.issend = false;
        }
    })

    // 机器人控制
    $('#controllers').modal({
        ready: () => {
            // socket 连接
            // if (CCB.boards.length > 0) {
            //     CCB.issend = true;
            //     CCB.socket && CCB.socket.emit('command', {
            //         cmd: 'open',
            //         option: { port: $('#ports').val(), baud: $('#serial_baud').val() }
            //     });
            // }
        },
        complete: () => {
            CCB.socket && CCB.socket.emit('command', { cmd: 'close' });
            CCB.issend = false;
        }
    })

    window.addEventListener('message', (e) => {
        if (e.data === 'open') {
            // socket 连接
            CCB.socket && CCB.socket.emit('command', {
                cmd: 'open',
                option: { port: $('#ports').val(), baud: $('#serial_baud').val() }
            });
        } else if (e.data === 'close') {
            // socket 关闭
            CCB.socket && CCB.socket.emit('command', { cmd: 'close' });
        }
    })


    $(".modale").modal({ dismissible: false })

    // Pop-up tool tips
    $('.tooltipped').tooltip({ 'delay': 50 });
    // Select menus
    // $('select').material_select();

    //scrollspy
    $('.scrollspy').scrollSpy();

    $('.modal_close').on('click', function () {
        $('.modal_closes').modal('close')
    })
    
    // 更新文件
    $("#updatePy").modal({
        ready: () => {
            // 获取 sd 卡的路径
            // pythoncmdselect('/sd/',function(data){return data})
            console.log('获取 sd 卡', pythoncmdselect('/sd/', function (data) {
                console.log(data)
            }))
        }
    })

    $('.confim').click(()=>{
        console.log('确定')
        $("#updatePy").modal('close')
    })

    $('.cancle').click(()=>{
        console.log('取消')
        $("#updatePy").modal('close')
    })

};

/** Binds the event listeners relevant to the page design. */
Ardublockly.bindDesignEventListeners = function () {
    // Resize blockly workspace on window resize
    window.addEventListener(
        'resize', Ardublockly.resizeBlocklyWorkspace, false);
};

/**
 * Sets the toolbox HTML element to be display or not and change the visibility
 * button to reflect the new state.
 * When the toolbox is visible it should display the "visibility-off" icon with
 * no background, and the opposite when toolbox is hidden.
 * @param {!boolean} show Indicates if the toolbox should be set visible.
 */


Ardublockly.displayToolbox = function (show) {
    var toolbox = $('.blocklyToolboxDiv');
    var toolboxTree = $('.blocklyTreeRoot');
    if (show) {
        toolbox.show();
        toolbox.animate({ height: document.getElementById('content_blocks').style.height }, 300,
            function () {
                toolboxTree.css('overflow-y', 'auto');
                window.dispatchEvent(new Event('resize'));
            });
    } else {
        toolboxTree.css('overflow-y', 'hidden');
        toolbox.animate({ height: 38 }, 300, function () {
            toolbox.fadeOut(350, 'linear', function () {
                window.dispatchEvent(new Event('resize'));
                setTimeout(function () { toolbox.height(38); }, 100);
            });
        });
    }
};

/** Resizes the container for the Blockly workspace. */
Ardublockly.resizeBlocklyWorkspace = function () {
    var contentBlocks = document.getElementById('content_blocks');
    var wrapperPanelSize =
        Ardublockly.getBBox_(document.getElementById('blocks_panel'));

    if (document.documentElement.clientWidth < 993) {
        let footer = document.getElementById('footer_');
        if (document.getElementById('Serial-monitor').style.display == 'none') {
            let Ardunio = Ardublockly.getBBox_(document.getElementById('codeArea'));
            let Ardunio1 = Ardublockly.getBBox_(document.getElementById('uploader'));
            footer.style.marginTop = Ardunio.height + Ardunio1.height + 'px';
        } else {
            let height = Ardublockly.getBBox_(document.getElementById('Serial-monitor'))
            footer.style.marginTop = height.height + 'px'
        }
    } else {
        document.getElementById('footer_').style.marginTop = 0
    }
    contentBlocks.style.top = wrapperPanelSize.y + 'px';
    contentBlocks.style.left = wrapperPanelSize.x + 'px';
    // Height and width need to be set, read back, then set again to
    // compensate for scrollbars.
    contentBlocks.style.height = wrapperPanelSize.height + 'px';
    contentBlocks.style.height =
        (2 * wrapperPanelSize.height - contentBlocks.offsetHeight) + 'px';
    contentBlocks.style.width = wrapperPanelSize.width + 'px';
    contentBlocks.style.width =
        (2 * wrapperPanelSize.width - contentBlocks.offsetWidth) + 'px';
};

/**
 * Sets the text for a "Materialize Modal" (like an android Dialog) to have
 * alert-like HTML messages.
 * @param {!string} title HTML to include in title.
 * @param {!element} body HTML to include in body.
 * @param {boolean=} confirm Indicates if the user is shown and option to just
 *     'Ok' or 'Ok and cancel'.
 * @param {string=|function=} callback If confirm option is selected this would
 *     be the function called when clicked 'OK'.
 */
Ardublockly.materialAlert = function (title, body, confirm, callback) {
    $('#gen_alert_title').text(title);
    $('#gen_alert_body').text('');
    $('#gen_alert_body').append(body);
    if (confirm == true) {
        $('#gen_alert_cancel_link').css({ 'display': 'inline-block' });
        if (callback) {
            $('#gen_alert_ok_link').bind('click', callback);
        }
    } else {
        $('#gen_alert_cancel_link').css({ 'display': 'none' });
        $('#gen_alert_ok_link').unbind('click');
    }
    $('#gen_alert').modal('open');
    window.location.hash = '';
};

Ardublockly.exampleAlert = function (title, body, confirm, callback) {
    $('#example_alert_body').text('');
    $('#example_alert_body').append(body);
    $('#example_alert').modal('open');
    $('#loading').css({'display':'block'});
    window.location.hash = '';
};

Ardublockly.customAlert = function (title, body, customText, callback) {
    $('#cus_alert_title').text(title);
    $('#cus_alert_body').text('');
    $('#cus_alert_body').append(body);
    if (customText) {
        $('#cus_alert_button_content').text(customText);
        if (callback) {
            $('#cus_alert_button').bind('click', callback);
        }
    } else {
        $('#cus_alert_button').unbind('click');
    }
    $('#cus_alert').modal('open');
    window.location.hash = '';
};


/**
 * Opens the modal that allows selection on additional toolbox categories.
 * @param {!element} htmlContent HTML to include in modal body.
 */
Ardublockly.openAdditionalBlocksModal = function (htmlContent) {
    $('#blocks_menu_body').text('');
    $('#blocks_menu_body').append(htmlContent);
    $('#blocks_menu').openModal({
        dismissible: true,
        opacity: .5,
        in_duration: 200,
        out_duration: 250
    });
};

/**
 * Creates an HTML node with the blocks category information from arguments.
 * @param {!string} title Text to include as category title.
 * @param {!string} description TExt to include in as description.
 * @param {!function} clickBind Function to bind to the tick box click.
 * @return {!element} HTML element to display the category content.
 */
Ardublockly.createExtraBlocksCatHtml = function (title, description, clickBind) {
    var tickId = title.replace(/\s+/g, '');
    var tickHtml = document.createElement('input');
    tickHtml.type = 'checkbox';
    tickHtml.id = tickId;
    tickHtml.addEventListener('click', function () {
        clickBind(document.getElementById(tickId).checked);
    });
    var tickLabelHtml = document.createElement('label');
    tickLabelHtml.htmlFor = tickId;
    tickLabelHtml.className = 'modal_label_title';
    tickLabelHtml.appendChild(document.createTextNode(title));
    var separatorHtml = document.createElement('div');
    separatorHtml.className = 'divider';
    var descriptionHthml = document.createElement('div');
    descriptionHthml.appendChild(document.createTextNode(description));

    var htmlContent = document.createElement('div');
    htmlContent.className = 'modal_section';
    htmlContent.appendChild(tickHtml);
    htmlContent.appendChild(tickLabelHtml);
    htmlContent.appendChild(separatorHtml);
    htmlContent.appendChild(descriptionHthml);
    return htmlContent;
};

/**
 * Displays a short message for 4 seconds in the form of a Materialize toast.
 * @param {!string} message Text to be temporarily displayed.
 */
Ardublockly.MaterialToast = function (message) {
    Materialize.toast(message, 4000, 'shareUrl');
};

/**
 * Initialises the sketch name input text JavaScript to dynamically adjust its
 * width to the width of its contents.
 */
Ardublockly.sketchNameSizeEffect = function () {
    var resizeInput = function () {
        $(this).attr('size', $(this).val().length);
    };

    var correctInput = function () {
        // If nothing in the input, add default name
        if ($(this).val() == '') {
            // $(this).val(Ardublockly.LOCALISED_TEXT.sketch_name);
            $(this).attr('size', 8);
        }
        // Replace all spaces with underscores
        $(this).val($(this).val().replace(/ /g, '_'));
    };

    var sketchNameInput = $('#sketch_name');
    sketchNameInput.keydown(resizeInput).each(resizeInput);
    sketchNameInput.blur(correctInput);
};

/**
 * Sets a string to the SketchName input field and triggers the events set from
 * Ardublockly.sketchNameSizeEffect().
 * @param {string?} newName Optional string to place in the sketch_name input.
 */
Ardublockly.sketchNameSet = function (newName) {
    var sketchNewName = newName || '';
    var sketchNameInput = $('#sketch_name');
    sketchNameInput.val(sketchNewName);
    sketchNameInput.attr('size', sketchNewName.length);
    sketchNameInput.keydown();
    sketchNameInput.blur();
};

/**
 * Initialises the sketch name input text JavaScript of the cloud
 * to dynamically adjust its width to the width of its contents.
 */
Ardublockly.cloudSketchNameSizeEffect = function () {
    var resizeInput = function () {
        $(this).attr('size', $(this).val().length);
    };

    var correctInput = function () {
        // If nothing in the input, add default name
        if ($(this).val() == '') {
            $(this).val('Untitled.xml');
            $(this).attr('size', 10);
        }
        // Replace all spaces with underscores
        $(this).val($(this).val().replace(/ /g, '_'));
    };

    var cloudSketchNameInput = $('#cloud_sketchName');
    cloudSketchNameInput.keydown(resizeInput).each(resizeInput);
    cloudSketchNameInput.blur(correctInput);
};

/**
 * Sets a string to the SketchName input field of the cloud and triggers the events set from
 * Ardublockly.sketchNameSizeEffect().
 * @param {string?} newName Optional string to place in the sketch_name input.
 */
Ardublockly.cloudSketchNameSet = function (newName) {
    var cloudSketchNewName = newName || '';
    var cloudSketchNameInput = $('#cloud_sketchName');
    cloudSketchNameInput.val(cloudSketchNewName);
    cloudSketchNameInput.attr('size', cloudSketchNewName.length);
    cloudSketchNameInput.keydown();
    cloudSketchNameInput.blur();
};

/**
 * Compute the absolute coordinates and dimensions of an HTML element.
 * @param {!Element} element Element to match.
 * @return {!Object} Contains height, width, x, and y properties.
 * @private
 */
Ardublockly.getBBox_ = function (element) {
    var height = element.offsetHeight;
    var width = element.offsetWidth;
    var x = 0;
    var y = 0;
    do {
        x += element.offsetLeft;
        y += element.offsetTop;
        element = element.offsetParent;
    } while (element);
    return {
        height: height,
        width: width,
        x: x,
        y: y
    };
};