<%-
	require "luci.sys"
	require "nixio.fs"
	local url=luci.sys.exec("uci get dota.@dota[0].url | xargs echo -n") or ""
	local filename=luci.sys.exec("uci get dota.@dota[0].filename | xargs echo -n") or ""
-%>


<script type="text/javascript">//<![CDATA[

function init_dota_page()
{
	var table = document.getElementById('dot');
	$("#dot tbody tr").remove();
    //console.log('init_dota_page clear table');

	var updatebtn = document.getElementById('updatebtn');
	var stxhr = new XHR();
	stxhr.get('<%=luci.dispatcher.build_url("admin", "services", "dota")%>/dota_init' , null,
		function(x, mArray)
		{
		}
		);
	<% if url ~= ""  and filename ~= "" then %>
		updatebtn.disabled = false;
	<%end%>
} 

function update_firmware()
{
    $("#dot tbody tr").remove();
    //console.log('clear table');
	var stxhr = new XHR();
	stxhr.get('<%=luci.dispatcher.build_url("admin", "services", "dota")%>/dota_update' + '/' + "C" + '/' + "update" + '/' + "custom" + '/' + "<%=filename%>" , null,
		function(x, mArray)
		{
			if (mArray && mArray.length && mArray.length > 0)
			{
				var min = 0;
				var data="";
				var max=mArray.length;
				for (i = min; i < max; i++) {
					data = data + mArray.firmwares[i] + ".";
				}
				<!--alert(data);-->
			}else if (mArray && mArray.length){
				<!--alert("Could not finish updating.");-->
			}  
		}
		);
}
let rebootTimer = null;
let errorTimer = null;
XHR.poll(
    10,
    '<%= luci.dispatcher.build_url("admin","services","dota","dota_status") %>',
    { status: 1 },
    
    function (status, payload) {
        
        if (status === 0) {               /* 0 ⇒ TCP error / CORS / timeout */
            const tbl  = document.getElementById('dot');
            if (!tbl) return;
            /* if we haven't already inserted the warning row, add it */
            if (!document.getElementById('dot-disconnected')) {
                const row  = tbl.insertRow(-1);
                const cell = row.insertCell(0);
                cell.id        = 'dot-disconnected';
                cell.className = 'cbi-value-error';
                cell.textContent = _('Disconnected – device not reachable');
                //console.log('add disconnected0');
            }
            return; /* skip normal parsing */
        }

        const list = Array.isArray(payload) ? payload : /* normal response */
                     (payload && payload.data) ? payload.data : [];
        //console.log('list:'+list.length);
        const tbl = document.getElementById('dot');
        if (!tbl) return;
        if (list.length==0 || tbl.rows.length > list.length)
        {
            $("#dot tbody tr").remove();
            //console.log('clear table');
            return;
        }
        let w = document.getElementById('dot-disconnected');
        if(w) 
        {
            //console.log('has disconnected or failed!');
            return;
        }
        let have = tbl.rows.length;
        //console.log('table1:'+tbl.rows.length);
        for (let i = have; i < list.length; i++) {
            const row  = tbl.insertRow(-1);
            const cell = row.insertCell(0);
            cell.innerHTML = list[i];
            //console.log('add '+list[i]);
        }
        /* ── check for known messages ─────────────────────────────── */
        const failed = list.some(l => typeof l === 'string' &&
                                       l.toLowerCase().includes('failed to update firmware'));
        if(failed)
        {
            const dlg = document.querySelector('.modal');
            if(L.ui.modal || dlg) 
            {
                L.ui.hideModal();
            }
            if(rebootTimer)
            {
                clearTimeout(rebootTimer);
                rebootTimer=null;
            }
            if(errorTimer)
            {
                clearTimeout(errorTimer);
                errorTimer=null;
            }
            /* if we haven't already inserted the warning row, add it */
            if (!document.getElementById('dot-disconnected')) {
                const row  = tbl.insertRow(-1);
                const cell = row.insertCell(0);
                cell.id        = 'dot-disconnected';
                cell.className = 'cbi-value-error';
                cell.textContent = _('Firmware update failed!!!');
                //console.log('add disconnected1');
            }
        }
        else if (rebootTimer === null) {                // only once
            const hit = list.some(l => typeof l === 'string' &&
                                       l.toLowerCase().includes('warning: updating firmware'));
            if (hit) {
                // Show reboot modal immediately
                L.ui.showModal(_('Rebooting...'), [
                    E('p', { 'class': 'spinning' }, _('Waiting for the device to reboot...'))
                ]);
                rebootTimer = setTimeout(function() {
                    L.ui.awaitReconnect(window.location.host, '192.168.1.1').then(() => {
                        // Success: Clear the modal when the device reconnects
                        L.ui.hideModal();
                    }).catch(() => {
                        // Failure: Show a warning message after reconnection timeout
                        L.ui.showModal(_('Rebooting...'), [
                            E('p', { 'class': 'spinning alert-message warning' },
                                _('Device unreachable! Still waiting for the device to come back online...'))
                        ]);
                    });
                }, 240000);
                // Show a warning if the device is unreachable within 300 seconds
                errorTimer = window.setTimeout(function() {
                    L.ui.showModal(_('Rebooting...'), [
                        E('p', { 'class': 'spinning alert-message error' },
                            _('The device is unreachable. Verify network configuration changes or confirm the device is powered on.'))
                    ]);
                }, 300000);
            } 
        }
    },
    30000   /* 30second timeout */
);

	//]]></script> 
	<body onload="init_dota_page()">
		<div id="buttoncss" align="center">
			<table class="cbi-section-table" style="width:940px; margin-left:5px">
				<input id="updatebtn" onclick="update_firmware()" type="button" disabled="false" value="<%:Update now%>" class="cbi-button cbi-button-apply"/>
			</table>
		</div>
        <br>
        <table width="100%" cellspacing="10" id="dot" class="table-striped"></table>
		<fieldset class="cbi-section">
			
		</fieldset>
	</body>
