<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Aisky-Sixth</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- 新 Bootstrap4 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/4.1.0/css/bootstrap.min.css">
    <!-- jQuery文件。务必在bootstrap.min.js 之前引入 -->
    <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
    <!-- popper.min.js 用于弹窗、提示、下拉菜单 -->
    <script src="https://cdn.bootcss.com/popper.js/1.12.5/umd/popper.min.js"></script>
    <!-- 最新的 Bootstrap4 核心 JavaScript 文件 -->
    <script src="https://cdn.bootcss.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
    <!--可用來建立使用者小圖示-->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.dev.js"></script>
<!--    <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js"></script>-->
<!--    <script src="https://cdn.socket.io/4.0.1/socket.io.min.js" integrity="sha384-LzhRnpGmQP+lOvWruF/lgkcqD+WDVt9fU3H4BWmwP5u5LTmkUGafMcpZKNObVMLU" crossorigin="anonymous"></script>-->

    <style>
        body {
	        margin:0;
        }

        .navbar-dark .navbar-nav .nav-link {
            color: white;
            cursor: pointer;
	        text-decoration:none;
            width: 130px;
            height: 46px;
        }

        .nav-top {
	        line-height:40px;
	        background-color: #C4C4C4;
        }

        .website_title{
            font-family: Roboto;
            font-style: normal;
            font-weight: normal;
            font-size: 30px;
            color: #000000;
        }

        .navbar-nav > li{
	        float: none;
	        display: inline-block;
	        width: 110px;
            margin: 0 auto;
            text-align: center;
        }

        .navbar-nav > li a{
            font-size: 20px;
        }

        .main-page {
            margin-top: 150px;
        }

        .page-title {
            font-family: Roboto;
            font-style: normal;
            font-weight: bold;
            font-size: 36px;
        }


        .flex {
            display: flex;
            flex-direction: row;
            flex-wrap: wrap;
            justify-content: center;
        }

          .set-link {
            display: inline-block;
            width: 350px;
            height: 100px;
            line-height: 100px;
            background: #008CBA;
            border: 1px solid #CFCFCF;
            box-sizing: border-box;
            color: #FFFFFF;
            border-radius: 10px;
            font-size: 36px;

        }

        .fa{
            display: inline-block;
            font: normal normal normal 14px/1 FontAwesome;
            font-size: inherit;
            text-rendering: auto;
            -webkit-font-smoothing: antialiased;
        }

        .fa-user-o:before{
            content: "\f2c0";
        }

        button {
            cursor: pointer;
        }


        @media(max-width:373px){
            .card {
                margin-right: 0px;
            }
        }

        @media(max-width:577px){

        }

        @media(min-width:576px){


        }
         @media(min-width:768px){
            .navbar-nav > li {
                 margin-left: 0px;
            }
            .navbar-nav .li-block {
                display:none;
            }
         }

         @media(min-width:991px){
            .navbar-nav > li {
                 margin-left: 20px;
            }
            .navbar-nav .li-block {
                display:none;
            }
         }

         @media(min-width:1200px){
            .navbar-nav > li {
                 margin-left: 35px;
            }
            .navbar-nav .li-block {
                display: inline-block;
                width: 100px;
            }
         }

         @media(min-width:1400px){
            .navbar-nav .li-block {
                display: inline-block;
                width: 200px;
            }

         }


         @media(min-width:1689px) {
            .navbar-nav > li {
                 margin-left: 50px;
            }
            .navbar-nav .li-block {
                display: inline-block;
                width: 500px;
            }
         }


    </style>

		<script>
            // // 原本就註解
            // //驗證token，如果不符合或過期就登出回登入頁
            // var str = localStorage.getItem('Hello');
            // $.ajax({
            //     type: "GET",
            //     url: "/auth",
            //     headers: {'Authorization': 'Bearer ' + str},
            //     success: function(result){
            //         console.log(result.identity);
            //     },
            //     error: function(result){
            //         window.location.href='/logout';
            //     }
            // });
            

            var install_item_list = [];             // 所有安裝的套件 1-1.  python3.8
            const STATUS = '{{params.STATUS}}';
            console.log("STATUS: " + STATUS);
            $(document).ready(function(){
                if (STATUS === '3') {
                    document.getElementById("Item3").checked = false;
                    document.getElementById("Item5").checked = false;
                    document.getElementById("Item3").setAttribute('disabled', 'disabled');
                    document.getElementById("Item5").setAttribute('disabled', 'disabled');
                }
                package_update();
            })

            $(function(){
                var namespace = '/test_conn';
                var url = 'http://127.0.0.1';
                var port = '5000';
                // var socket = io.connect(url + ':' + port + namespace);
            });

            function package_update() {
                // console.log("install_item_list: " + install_item_list);
                var select_install_item_list = install_item_list.slice();
                var Item_select_list = [];              // 勾選欲安裝的項目
                for (let i = 1; i < 9; i++) {
                    var install_item_true = document.getElementById("Item" + i).checked;
                    if (install_item_true) {
                        Item_select_list.push(String(i));
                    }
                }
                // console.log("Item_select_list: " + Item_select_list);

                for (let x = select_install_item_list.length-1; x >= 0; x--) {
                    if (Item_select_list.indexOf(select_install_item_list[x].substring(0,1)) == -1) {
                        select_install_item_list.splice(x, 1);
                    }
                }
                // console.log("select_install_item_list: " + select_install_item_list);
                
                item_table = '<h1>Item install status</h1>' + 
                            '<table  class="table table-bordered" style="font-size:23px;margin-top:30px;">' + 
                            '<tbody>' + 
                            '<tr><th>Item</th><th>Status</th></tr>';
                for (let itable = 0; itable < select_install_item_list.length; itable++) {
                    var package_index = select_install_item_list[itable].indexOf('.');
                    var package_name = select_install_item_list[itable].substring(package_index+1);
                    item_table += '<tr>' + 
                                  '<td>' + select_install_item_list[itable] + '</td>' + 
                                  '<td>' + 
                                  '<div class="progress" style="height:35px;">' + 
                                  '<div id="' + package_name + '-status" name="' + package_name + '-status" class="progress-bar progress-bar-striped" style="width:0%; height:35px; font-size:20px; color:black; text-align:center;">0%</div>' + 
                                  '</div>' + 
                                  '</td>' + 
                                  '</tr>';
                }
                item_table += '</tbody>' + '</table>';

                var target_item = document.getElementById("install_items");
                target_item.innerHTML = '';
                target_item.innerHTML = item_table;
                
            }

        </script>
</head>





<body>
    <nav class="fixed-top">
        <nav class="navbar navbar-expand-md nav-top justify-content-center">
            <div>
                <span class="website_title">伺服器建置</span>
            </div>
        </nav>
        <nav class="navbar navbar-expand-md bg-dark navbar-dark nav-bottom">
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="collapsibleNavbar">
                <ul class="navbar-nav">
                    <li class="nav-item">
                        <a class="nav-link" href="/">首頁</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/incoming_check">進貨檢測</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/burn_program">感測器燒錄</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/modify_permissions">權限設置</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/add_sensor">新增感測器</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/add_server">伺服器建置</a>
                    </li>
                    <li class="li-block"></li>
                    <li class="nav-item">
                        <a class="nav-link" href="#"><i class="fa fa-user-o"></i> {{params.username}}</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/logout">Logout</a>
                    </li>
                </ul>
            </div>
        </nav>
    </nav>
    <div class="main-page">
        <div class="container">
            <div class="row">
                <div class="col" style="margin: auto; ">
                    <!-- 說明文件 -->
                    <div style="text-align:center; font-size: 23px; color: crimson;">
                        <a href="http://60.250.156.230:3000/Automatic_build_system/Automatically_install_files/src/master/README.md"
                            target="_blank">自動布建伺服器環境建置手冊</a>
                    </div>

                    <table  class="table table-bordered" style="font-size:23px;margin-top:30px;">
                        <tbody>
                            <tr>
                                <td>1.請輸入您的IP位置:</td>
                                <td><input type="text" name="user_ip" value="60.250.156.232"></td>
                            </tr>
                            <tr>
                                <td>2.請輸入您的登入帳號:</td>
                                <td><input type="text" name="user_loginname" value="root"></td>
                            </tr>
                            <tr>
                                <td>3.請輸入您的username:</td>
                                <td><input type="text" name="user_username" value="gs1802"></td>
                            </tr>
                            <tr>
                                <td>4.請輸入您的password:</td>
                                <td><input type="password" name="user_password" value="g53743001"></td>
                            </tr>

                            <!-- 勾選安裝套件 -->
                            <tr>
                                <th>請勾選欲安裝之套件</th>
                                <td>
                                    <input type="checkbox" class="" id="Item1" onclick="package_update()" checked>
                                    <label for="Item1">Item1 - Common Command</label><br>
                                    <input type="checkbox" class="" id="Item2" onclick="package_update()" checked>
                                    <label for="Item2">Item2 - LAMP</label><br>
                                    <input type="checkbox" class="" id="Item3" onclick="package_update()" checked>
                                    <label for="Item3">Item3 - MQTT Server</label><br>
                                    <input type="checkbox" class="" id="Item4" onclick="package_update()" checked>
                                    <label for="Item4">Item4 - Watchdog</label><br>
                                    <input type="checkbox" class="" id="Item5" onclick="package_update()" checked>
                                    <label for="Item5">Item5 - Git Server</label><br>
                                    <input type="checkbox" class="" id="Item6" onclick="package_update()" checked>
                                    <label for="Item6">Item6 - Python packegs Library</label><br>
                                    <input type="checkbox" class="" id="Item7" onclick="package_update()" checked >
                                    <label for="Item7">Item7 - AP(WebPage)</label><br>
                                    <input type="checkbox" class="" id="Item8" onclick="package_update()" checked>
                                    <label for="Item8">Item8 - ROS ubuntu 18.04 melodic</label>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                    <div class="text-center">
                        <input type="button" value="建置" name="add_server" style="cursor:pointer;" onclick="AddServer()">
                    </div>
                    <div class="text-center" id="addServer-status" style="margin-top:30px;color:red;visibility:hidden;">
                        <h2>伺服器建置中...</h2>
                    </div>
                    <div id="install_items">
                        <h1>Item install status</h1>
                        <table  class="table table-bordered" style="font-size:23px;margin-top:30px;">
                            <tbody>
                                <tr>
                                    <th>Item</th>
                                    <th>Status</th>
                                </tr>
                                {% for item in params.L %}
                                    <script>
                                        var item = '{{item}}';
                                        install_item_list.push(item);
                                    </script>
                                    <tr>
                                        <td>{{loop.index}}.{{item}}</td>
                                        <td>{{item}}</td>
                                        <td>
                                            <div class="progress" style="height:35px;">
                                                <div id="{{item}}-status" name="{{item}}-status" class="progress-bar progress-bar-striped" 
                                                    style="width:0%; height:35px; font-size:20px; color:black; text-align:center;">0%
                                                </div>
                                            </div>
                                        </td>
                                    </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
    <script>
            function AddBarIndex(obj){
                // console.log("obj: ", obj)
                var item = document.getElementById(obj);
                // console.log("item: ", item)
                //因假設元素id內有.或是空格的使用jQuery選擇器會找不到，所以改成用js的節點來設置
                //[0].style.width 讓width顯示為%值，使用css.('width')會顯示px
                //var width = obj[0].style.width;
                var width = item.style.width;
                // console.log("width: " + width);
                var current_width = width.substring(0, width.length-1);
                console.log("current_width: " + current_width);
                item.style.width = Number(current_width) + 2 + '%';
                // console.log("item.style.width: " + item.style.width);
                item.innerText = Number(current_width) + 2 + '%';
                // console.log("item.innerText: " + item.innerText);

                if (current_width == 94) {
                    console.log(obj + ' INSTALLATION AddBar Pause');
                    // eval('clearInterval(timer)');
                    clearInterval(timer);
                }
            };

            function AddServer(){
                //var item = document.getElementById('python3.8-status');
                //item.style.width = '2%';
                //item.innerText = '2%';
                //timer_python38 = window.setInterval("AddBarIndex('python3.8-status')", 2000);
                $("#addServer-status").css('visibility','visible');
                var ip = $("input[name=user_ip]").val();
                var loginname = $("input[name=user_loginname]").val();
                var username = $("input[name=user_username]").val();
                var password = $("input[name=user_password]").val();
                var item1_checked = document.getElementById("Item1").checked;
                var item2_checked = document.getElementById("Item2").checked;
                var item3_checked = document.getElementById("Item3").checked;
                var item4_checked = document.getElementById("Item4").checked;
                var item5_checked = document.getElementById("Item5").checked;
                var item6_checked = document.getElementById("Item6").checked;
                var item7_checked = document.getElementById("Item7").checked;
                var item8_checked = document.getElementById("Item8").checked;
                var json = { "ip":ip,
                             "loginname":loginname,
                             "username":username,
                             "password":password,
                             "item1_checked":item1_checked,
                             "item2_checked":item2_checked,
                             "item3_checked":item3_checked,
                             "item4_checked":item4_checked,
                             "item5_checked":item5_checked,
                             "item6_checked":item6_checked,
                             "item7_checked":item7_checked,
                             "item8_checked":item8_checked
                            };
                var abs_update_interval = window.setInterval("abs_update()", 1000);
                $.post('/add_server', json, function(resText){
                    $("#addServer-status").css('visibility','hidden');
                    if(resText == 'Authentication failed.'){
                        resText = '您輸入的密碼有誤，請重新輸入!';
                        $("input[name=user_ip]").val('');
                        $("input[name=user_username]").val('');
                        $("input[name=user_password]").val('');
                    };
                    clearInterval(abs_update_interval);
                    setTimeout(alert(resText), 1000);
                }, 'text');
            };

            Automatic_Build_System_installation = {
                'python3.8-installation': 'Wait',
                'python3-pip-installation': 'Wait',
                'cryptography-installation': 'Wait',
                'upgrade-installation': 'Wait',
                'grep-installation': 'Wait',
                'git-installation': 'Wait',
                'gitpython-installation': 'Wait',
                'python3-tk-installation': 'Wait',
                'wget-installation': 'Wait',
                'python3-dev-installation': 'Wait',
                'default-libmysqlclient-dev-installation': 'Wait',
                'build-essential-installation': 'Wait',
                'tasksel-installation': 'Wait',
                'lamp-server-installation': 'Wait',
                'phpMyAdmin-5.1.0-all-languages.tar.gz-installation': 'Wait',
                'openssl-installation': 'Wait',
                'php-common-installation': 'Wait',
                'php-curl-installation': 'Wait',
                'php-json-installation': 'Wait',
                'php-mbstring-installation': 'Wait',
                'php-mysql-installation': 'Wait',
                'php-xml-installation': 'Wait',
                'php-zip-installation': 'Wait',
                'php7.2-mbstring-installation': 'Wait',
                'php7.2-xml-installation': 'Wait',
                'php7.2-mysql-installation': 'Wait',
                'php7.2-common-installation': 'Wait',
                'php7.2-curl-installation': 'Wait',
                'php7.2-json-installation': 'Wait',
                'php7.2-zip-installation': 'Wait',
                'apache2-installation': 'Wait',
                'paho-mqtt-installation': 'Wait',
                'mosquitto-installation': 'Wait',
                'mqtt_server_setting-installation': 'Wait',
                'rclocal/rc.local-installation': 'Wait',
                'golang-installation': 'Wait',
                'gogsfile-installation': 'Wait',
                'requirements-installation': 'Wait',
                'CoffeeProject-installation': 'Wait',
                'BBend-Test-JWT-installation': 'Wait',
                'Coffee_MySQL-installation': 'Wait',
                'chrony-installation': 'Wait',
                'ntpdate-installation': 'Wait',
                '--keyserver-installation': 'Wait',
                'update-installation': 'Wait',
                'ros-melodic-desktop-full-installation': 'Wait',
                'ros-melodic-rqt*-installation': 'Wait',
                'python-rosdep-installation': 'Wait',
                'python-rosinstall-installation': 'Wait',
                'python-rosinstall-generator-installation': 'Wait',
                'python-wstool-installation': 'Wait',
                'catkin_make-installation': 'Wait'
            }

            var abs_update_process = 0;
            var timer;
            function abs_update() {
                if (abs_update_process === 1) {
                    return;
                }
                
                abs_update_process = 1;
                $.ajax({
                    async:false,
                    type:"GET",
                    url:"/ABS_update",
                    dataType:"JSON",
                    success:function(response){
                        for (const key of Object.entries(response)) {
                            // console.log("TT" + response['requirements'])
                            if (response[key[0]] == 'Install') {
                                if (Automatic_Build_System_installation[key[0] + '-installation'] == 'Wait') {
                                    Automatic_Build_System_installation[key[0] + '-installation'] = 'Install';
                                    timer = window.setInterval("AddBarIndex(\"" + key[0] + "-status\")", 2000);
                                    // eval('var ' + key[0] + '_timer = window.setInterval("AddBarIndex(\"' + key[0] + '-status\")", 2000);')
                                    // alert('!!!')
                                }
                            } else if (response[key[0]] == '0') {
                                // pass
                            } else if (response[key[0]] == 'Error') {
                                if (Automatic_Build_System_installation[key[0] + '-installation'] == 'Install') {
                                    Automatic_Build_System_installation[key[0] + '-installation'] = 'Error';
                                    ItemInstallFail(timer, key[0]);
                                }
                            // } else if (response[key[0]] == 'Success') {
                            //     if (Automatic_Build_System_installation[key[0] + '-installation'] == 'Install') {
                            //         Automatic_Build_System_installation[key[0] + '-installation'] = 'Success';
                            //         ItemInstallSuccess(timer, key[0]);
                            //     }
                            // // ========== Rita 0428 測試保留 ==========
                            // } else if (Number(response[key[0]]) !== NaN) {
                            //     if (Automatic_Build_System_installation[key[0] + '-installation'] == 'Install') {
                            //         Automatic_Build_System_installation[key[0] + '-installation'] = 'Success';
                            //         ItemInstallSuccess(timer, key[0], response[key[0]]);
                            //     } 
                            // // ========== Rita 0428 測試保留 ==========
                            } else if (Number(response[key[0]]) !== NaN) {
                                // Automatic_Build_System_installation[key[0] + '-installation'] = response[key[0]];
                                // ItemInstallSuccess(timer, key[0], response[key[0]]);
                                if (Automatic_Build_System_installation[key[0] + '-installation'] == 'Install') {
                                    Automatic_Build_System_installation[key[0] + '-installation'] = response[key[0]];
                                    ItemInstallSuccess(timer, key[0], response[key[0]]);
                                } else if (Automatic_Build_System_installation[key[0] + '-installation'] == 'Wait') {
                                    Automatic_Build_System_installation[key[0] + '-installation'] = response[key[0]];
                                    console.log(key[0] + " : " + response[key[0]]);
                                    ItemInstallSuccess(timer, key[0], response[key[0]]);
                                }
                            } else {
                                console.log("response[key[0]]: " + response[key[0]]);
                            }
                        }
                        abs_update_process = 0;
                    },
                    error:function(thrownError){
                        console.log("thrownError: " + thrownError);
                        abs_update_process = 0;
                    }
                });
            };

            function ItemInstallSuccess(timer_item, item_name, execution_time){
                eval('clearInterval(' + timer_item + ')');
                var item = document.getElementById(item_name + '-status');
                item.style.width = '100%';
                item.innerText = execution_time + 's';
            };

            function ItemInstallFail(timer_item, item_name){
                eval('clearInterval(' + timer_item + ')');
                var item = document.getElementById(item_name + '-status');
                item.style.width = '0%';
                item.innerText = 'Fail';
                item.style.color = 'red';
                item.style.fontWeight = 'bold';
            };
    </script>
</html>