<%
	local util = require "luci.util"
	local fs = require "nixio.fs"
	local sys = require "luci.sys"
	local http = require "luci.http"
	local dispatcher = require "luci.dispatcher"
	local uci = require "luci.model.uci".cursor()

	local devv = tostring(uci:get("sms_tool", "general", "readport"))

	local smsmem = tostring(uci:get("sms_tool", "general", "storage"))

	local sms = tostring(luci.sys.exec("sms_tool -s" .. smsmem .. " -d " .. devv .. " -f '%Y-%m-%d %H:%M' -j recv 2>/dev/null"))
	local smsmer = tostring(uci:get("sms_tool", "general", "mergesms"))
	local smscuta = string.sub (sms, 8)
	local smscut = smscuta:sub(1, #smscuta - 2)
	local statusb = luci.util.exec("sms_tool -s" .. smsmem .. " -d ".. devv .. " status")
	local all = string.sub (statusb, -4)
	local location = ""
	local l = string.sub (statusb, 15, 16)
	if l == "SM" then
      		location = translate("SIM card")
 	end

	if l == "ME" then
      		location = translate("Modem memory")
 	end

-%>

<%+header%>

<!--
-- Copyright 2020-2021 Rafał Wabik (IceG) - From eko.one.pl forum
-- Licensed to the GNU General Public License v3.0.
-->

<style>

table {
  border-collapse: collapse;
  width: 100%;

}

th, td {
  border-bottom: 1px solid #ddd;
  font-size: 12px;
  padding: 10px;
  text-align: justify;
  display: table-cell;
  vertical-align: top;

}

tr:nth-child(odd) {background-color: #f5f5f5;}

</style>

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

	window.onload = function readSMS() {

			XHR.get('<%=luci.dispatcher.build_url("admin", "modem", "sms", "readsim")%>', null,
			function(x, sim)
			{
			var vn = parseInt(sim.use) || 0;
			var mn = parseInt(sim.all) || 100;
			var pc = Math.floor((100 / mn) * vn);
			document.getElementById('usse').innerHTML=sim.use  + " / " + sim.all + " " + '('+ pc + '%)';

			}
			);


			var msgm = <%=smsmer%>;
			if ( msgm == "0" ) {

			var array = <%=smscut%>;

			var sortedData = array .sort((function (a, b) { return new Date(b.timestamp) - new Date(a.timestamp) }));

			var table = document.getElementById("smsTable");
		
			var data = JSON.stringify(sortedData);

			var json = JSON.parse(data);

			var x = <%=all%>;
        		for (var d = 0; d < json.length; d++) {

            					row = table.insertRow(-1);
  						var cell1 = row.insertCell(0);
  						var cell2 = row.insertCell(0);
  						var cell3 = row.insertCell(0);
  						var cell4 = row.insertCell(0);

 				 		cell4.innerHTML = json[d].sender;
  						cell3.innerHTML = json[d].timestamp;
    						cell2.innerHTML = json[d].content;
						cell1.innerHTML = "<img class='btn cbi-button cbi-button-neutral' id="+"btn"+json[d].index+" src='<%=resource%>/icons/delsms.png' onclick='delete_me()'>"

					
				}
			}

			if ( msgm == "1" ) {


			var array = <%=smscut%>;

			var sortedData = array .sort((function (a, b) { return new Date(b.timestamp) - new Date(a.timestamp) }));

			var table = document.getElementById("smsTable");


			var MergeMySMS = sortedData;
    			result = [];

			MergeMySMS.forEach(function (o) {
    			if (!this[o.timestamp] && !this[o.sender]) {
        		this[o.timestamp] = { index: o.index, sender: o.sender, timestamp: o.timestamp, content: o.content };
        		result.push(this[o.timestamp]);
        		return;
    			}
			if (this[o.timestamp].sender == o.sender) {
    			this[o.timestamp].content += o.content;
    			this[o.timestamp].index += '-' + o.index;}
			else {
			this[o.timestamp] = { index: o.index, sender: o.sender, timestamp: o.timestamp, content: o.content };
        		result.push(this[o.timestamp]);
        		return;
			}
			}, Object.create(null));

		
			var data = JSON.stringify(result);

			var json = JSON.parse(data);

			var x = <%=all%>;
        		for (var d = 0; d < json.length; d++) {

            					row = table.insertRow(-1);
  						var cell1 = row.insertCell(0);
  						var cell2 = row.insertCell(0);
  						var cell3 = row.insertCell(0);
  						var cell4 = row.insertCell(0);

 				 		cell4.innerHTML = json[d].sender;
  						cell3.innerHTML = json[d].timestamp;
    						cell2.innerHTML = json[d].content;
						cell1.innerHTML = "<img class='btn cbi-button cbi-button-neutral' id="+"btn"+json[d].index+" src='<%=resource%>/icons/delsms.png' onclick='delete_me()'>"

					
				}


			}

	
	}


function refreshSMS() {

window.location.reload();

}


function delete_me()
{

	var str = event.srcElement.id;
	var n = str.length;

	var smsindex = str.substr(3, n);

	if (confirm("<%:Delete selected message?%>")) {


			var td = event.target.parentNode;
      			var tr = td.parentNode;
      			tr.parentNode.removeChild(tr);




		XHR.get('<%=luci.dispatcher.build_url("admin", "modem", "sms", "delete_one")%>/' + smsindex, null,

			function()
			{
			var totalRowCount = 0;
        		var rowCount = -2;
       		var table = document.getElementById("smsTable");
        		var rows = table.getElementsByTagName("tr")
        		for (var i = 0; i < rows.length; i++) {
            		totalRowCount++;
            		if (rows[i].getElementsByTagName("td").length > 0) {
                	rowCount++;
            		}
        		}
		XHR.get('<%=luci.dispatcher.build_url("admin", "modem", "sms", "readsim")%>', null,
			function(x, sim)
			{
			var vn = parseInt(sim.use) || 0;
			var mn = parseInt(sim.all) || 100;
			var pc = Math.floor((100 / mn) * vn);
			document.getElementById('usse').innerHTML=sim.use  + " / " + sim.all + " " + '('+ pc + '%)';


			}
			);
			}


		);



		XHR.get('<%=luci.dispatcher.build_url("admin", "modem", "sms", "countsms")%>/' , null,

			function()
			{
			
			}
		);


		return false;
		}
}

	function deleteall(btn)
	{

	if (confirm("<%:Delete all the messages?%>")) {


		var rowCount = smsTable.rows.length;
		document.getElementById('usse').innerHTML = "0"  + " / " + <%=all%>;
		for (var i = rowCount - 1; i > 0; i--) {
            		smsTable.deleteRow(i);}


		XHR.get('<%=luci.dispatcher.build_url("admin", "modem", "sms", "delete_all")%>/' , null,

			function()
			{
			document.getElementById('usse').innerHTML = "0"  + " / " + <%=all%> + " " + '(0%)';
			}
		);

		XHR.get('<%=luci.dispatcher.build_url("admin", "modem", "sms", "countsms")%>/' , null,

			function()
			{
			
			}
		);

		return false;
		}
	}

//]]></script>


<h2><%:SMS Messages%></h2>
	<label><%:Web UI for handling messages via sms_tool.%></label>
	<p></p>
	<h4><%:Received Messages%></h4>
	<div class="table" width="100%">
	<div class="tr"><div class="td left" width="33%"><%:Messages store in%>:</div><div class="td left"><%=location%></div></div>
	<div class="tr"><div class="td left" width="33%"><%:Messages (Inbox / Maximum)%>:</div><div class="td left" id="usse"></div></div>
	</div>

	<table id="smsTable" width="100%" class="table">
  	<tr class="tr cbi-rowstyle-2">

    	<td class="td left" width="15%"><strong><%:From%></strong></td>
    	<td class="td left" width="15%"><strong><%:Received%></strong></td>
    	<td class="td center" width="62%" ><strong><%:Message%></strong></td>
    	<td class="td center" width="8%"><strong></strong></td>
 	</tr>
	</table>

	<div class="table" width="100%" >
    	<div class="tr cbi-rowstyle-2">
	
	
	<div class="td right" style="width:100%;">
	<div style="float: left;"><div class="ifacebadge"><a href="https://eko.one.pl/forum/viewtopic.php?id=20096">e1</a></div></div>
	<input type="button" id="delbtn" class="btn cbi-button cbi-button-neutral" value="<%:Refresh SMS%>" onclick="refreshSMS()" />&nbsp;&nbsp;&nbsp;<input type="button" id="delabtn" class="btn cbi-button cbi-button-neutral" value="<%:Delete All%>" onclick="deleteall(this)" />

	</div>

	</div>


<%+footer%>
