
<%+header%> 

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

function init_dota_page()
{
	var firmware = document.getElementById("firmware");
	var length = firmware.options.length;
	firmware.selectedIndex = 0;
	for (i = 1; i < length; i++) {
		firmware.remove(1);
	}
	var table = document.getElementById('dot');
	$("#dot tbody tr").remove();
    //console.log('init_dota_page clear table');

	var updatebtn = document.getElementById('updatebtn');
	var checkbtn = document.getElementById('checkbtn');
	var stxhr = new XHR();
	stxhr.get('<%=luci.dispatcher.build_url("admin", "services", "dota")%>/dota_init' , null,
		function(x, mArray)
		{
		}
		);
	updatebtn.disabled = true;
	checkbtn.disabled = false;
	firmware.disabled = true;
} 

function toggleupdate()
{
	var updatebtn = document.getElementById('updatebtn');
	var firmware = document.getElementById("firmware");
	if(firmware.selectedIndex==0)
		updatebtn.disabled = true;
	else{
		updatebtn.disabled = false;
	}
} 

function check_firmware()
{
	var i=0;
	var updatebtn = document.getElementById('updatebtn');
	updatebtn.disabled=true;
	var checkbtn = document.getElementById('checkbtn');
	checkbtn.disabled = true;
	var firmware = document.getElementById("firmware");
	var length = firmware.options.length;
	firmware.selectedIndex = 0;
	for (i = 1; i < length; i++) {
		firmware.remove(1);
	}
	var table = document.getElementById('dot');
	$("#dot tbody tr").remove();
    //console.log('check_firmware clear table');


	var channel = document.getElementById('channel');
	var channelval=channel.value;
	var stxhr = new XHR();
	stxhr.get('<%=luci.dispatcher.build_url("admin", "services", "dota")%>/dota_update' + '/' + "M" + '/' + "check" + '/' + channelval + '/' + "NULL", null,
		function(x, mArray)
		{
			if (mArray.length > 0)
			{
				if(mArray.length && mArray.length==1)
				{
					checkbtn.disabled = false;
					<!--alert(mArray.firmwares[0]);-->
				}else{
					var min = 1;
					var max=mArray.length;
					var latest=mArray.firmwares[0];
					for (i = min; i < max; i++) {
						var opt = document.createElement('option');
						opt.value = mArray.firmwares[i];
						opt.innerHTML = mArray.firmwares[i];
						firmware.appendChild(opt);
					}
					if( latest=="new"){
						firmware.selectedIndex = 1;
						updatebtn.disabled=false;
					}else{
						firmware.selectedIndex = 0;
					}
					checkbtn.disabled = false;
				}
			}else{
				checkbtn.disabled = false;
				<!--alert("Could not finish checking.");-->
			}
		}
		);
	firmware.disabled = false;
}
function update_firmware()
{
	var channel = document.getElementById('channel');
	var channelval=channel.value;
	var firmware = document.getElementById('firmware');
	var filename=firmware.value;
	var updatebtn = document.getElementById('updatebtn');
//	var forceupgrade = document.getElementById('forceupgrade').checked;					/MH-1893

	if (filename != "NULL") {
		firmware.disabled = true;
		var checkbtn = document.getElementById('checkbtn');
		checkbtn.disabled = true;
		channel.disabled=true;
		updatebtn.disabled=true;
		if (0 && forceupgrade){
			upgrade="fupdate"
		}else{
			upgrade="update"
		}
        var table = document.getElementById('dot');
        $("#dot tbody tr").remove();
        //console.log('check_firmware clear table');
		var stxhr = new XHR();
		stxhr.get('<%=luci.dispatcher.build_url("admin", "services", "dota")%>/dota_update' + '/' + "M" + '/' + upgrade + '/' + channelval + '/' + 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.");-->
				}  
			}
			);
	}else{
		<!--alert("Please select Proper firmware to upload");-->
	}
}

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()">
		<h2><a>Download Over The Air</a></h2>
		<div id="buttoncss" align="center">
			<table class="cbi-section-table" style="width:940px; margin-left:5px">
				<tr class="cbi-section-table-descr">
					<th class="cbi-section-table-cell" style="width:100px"><%:Channel%></th>
					<th class="cbi-section-table-cell" style="width:100px"><%:Check for update%></th>
					<th class="cbi-section-table-cell" style="width:350px"><%:Available Firmwares%></th>
					<!-- <th class="cbi-section-table-cell" style="width:50px"><%:Force Upgrade%></th> -->  <!-- EPKN-1122 -->
					<th class="cbi-section-table-cell" style="width:100px"><%:Upgrade / Downgrade%></th>
				</tr>
				<tr>
					<td>
						<select id="channel" onchange="init_dota_page()" class="cbi-input-select" name="channel">
							<option value="released" selected="selected">Released</option>
							<option value="beta">Beta</option>
							<option value="development">Development</option>
						</select>
					</td>
					<td>
						<input  id="checkbtn" onclick="check_firmware()" type="button" value="<%:Check for update%>" class="cbi-button cbi-button-apply"/>
					</td>   
					<td>
						<select id="firmware" onchange="toggleupdate()" disabled  style="width:350px" class="cbi-input-select" name="firmware">
							<option value="NULL" selected="selected">Please Select from below firmwares</option>
						</select>
					</td>
<!-- EPKN-1122 -->
			<!--	<td>
						<input  id="forceupgrade" type="checkbox"/>
					</td> 
			-->
					<td>
						<input id="updatebtn" onclick="update_firmware()" type="button" disabled value="<%:Update now%>" class="cbi-button cbi-button-apply"/>
					</td>
				</tr>
			</table>
		</div>
        <br>
        <table width="100%" cellspacing="10" id="dot" class="table-striped"></table>
		<fieldset class="cbi-section">
			
		</fieldset>
	</body>

<%+footer%> 

