<!DOCTYPE html>

  <html lang="en">

  <head>
    <meta charset="UTF-8">
    <title>Auto Upload SpotRep - K9RCP</title>
<style>
html { 
  background: url('images/bg.jpg') no-repeat center center fixed; 
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

#status-bar {
    position: absolute;
    margin: 0 0 0 0;
    left: 0px;
    bottom: 0px;
    z-index: 1;
    padding: 0px;
    width: 100%;
	background-color: white;
}
#main{
  -moz-border-radius:10px;
  -webkit-border-radius:10px;
  border-radius:10px;
  background: #fff; /* fallback for browsers that don't understand rgba */
  border: solid 10px #000; /* fallback for browsers that don't understand rgba */
  background-color: rgba(255,255,255,0.8); /* slighly transparent white */
  border-color: rgba(0,0,0,0.2); /*Very transparent black*/
}
</style>
  </head>

  <body>
 
    <div id="main"><center>
<table style="width:100%">
  <tr>
    <td>Callsign: <input type="text" id="callsign" onkeyup="updateCall()" name="name" required
       minlength="3" maxlength="8" size="10" /><span id="file-status"></span></td>
    <td><center><div id="status"></div></center></td>
  </tr>
  
</table>
<button onclick="gui.Shell.openExternal('http://k9rcp-server.local.mesh/spotrep/');">View Data</button>
	</center>
	</div>
	<div id="status-bar"> Status: </div>
	<script src="./md5.js"></script>
    <script>
	      var gui = require('nw.gui');
        var win = gui.Window.get();
        win.on('new-win-policy', function (frame, url, policy) {
            policy.forceNewPopup();
        });
	function mf(formato) {
    var hor, hor2, x;
    var fechai = new Date();
    var ano = fechai.getYear() + 1900;
    var ano2 = ("" + (fechai.getYear() + 1900)).slice(-2);
    var mes = ("0" + (fechai.getMonth() + 1)).slice(-2);
    var dia = ("0" + fechai.getDate()).slice(-2);
    hor = hor2 = ("0" + fechai.getHours()).slice(-2);
    hor2 = fechai.getHours();
	if (fechai.getHours() > 12) {
        hor2 = fechai.getHours() - 12;
	}
	
	
    if (fechai.getHours() > 11) {
             x = "PM";
    } else {
        x = "AM";
    }
    var min = ("0" + fechai.getMinutes()).slice(-2);
    var seg = ("0" + fechai.getSeconds()).slice(-2);
    var fecha = formato.reemplaza("YyMDHhISx".split(''), [ano, ano2, mes, dia, hor, hor2, min, seg, x]);
    return fecha;
}
String.prototype.reemplaza = function(busca, reemplaza) {
    var b = Array.isArray(busca);
    var r = Array.isArray(reemplaza);
    var ret = this;
    if (b) {
        for (var i in busca) {
            var c = r ? (reemplaza[i] ? reemplaza[i] : "") : reemplaza;
            ret = ret.replace(new RegExp(busca[i], 'g'), c);
        }
    } else {
        var c = r ? reemplaza[0] : reemplaza;
        ret = ret.replace(new RegExp(busca, 'g'), c);
    }
    return ret;
}

function memorySizeOf(obj) {
    var bytes = 0;

    function sizeOf(obj) {
        if(obj !== null && obj !== undefined) {
            switch(typeof obj) {
            case 'number':
                bytes += 8;
                break;
            case 'string':
                bytes += obj.length * 2;
                break;
            case 'boolean':
                bytes += 4;
                break;
            case 'object':
                var objClass = Object.prototype.toString.call(obj).slice(8, -1);
                if(objClass === 'Object' || objClass === 'Array') {
                    for(var key in obj) {
                        if(!obj.hasOwnProperty(key)) continue;
                        sizeOf(obj[key]);
                    }
                } else bytes += obj.toString().length * 2;
                break;
            }
        }
        return bytes;
    };

    function formatByteSize(bytes) {
        if(bytes < 1024) return bytes + " bytes";
        else if(bytes < 1048576) return(bytes / 1024).toFixed(3) + " KiB";
        else if(bytes < 1073741824) return(bytes / 1048576).toFixed(3) + " MiB";
        else return(bytes / 1073741824).toFixed(3) + " GiB";
    };

    return formatByteSize(sizeOf(obj));
};

var updateXml, lastMd,callSign;

function updateCall() {
	callSign = document.getElementById("callsign").value.toUpperCase();
	document.getElementById("callsign").value = document.getElementById("callsign").value.toUpperCase();
	console.error(document.getElementById("callsign").value.toUpperCase());
  if (fs.existsSync('/RMS Express/'+callSign+'/FormData/SPOTREP-2.txt')) {
    		document.getElementById("file-status").innerHTML = ' <img src="./images/good.png" width="24px" />';
		  		clearInterval(updateXml);
		runapipull();
		lastMd = 0;

}
if (!fs.existsSync('/RMS Express/'+callSign+'/FormData/SPOTREP-2.txt')) {
document.getElementById("file-status").innerHTML = ' <img src="./images/bad.png" width="24px" />';
document.getElementById("status-bar").innerHTML = 'Error: File does not exist: C:\\RMS Express\\'+callSign+'\\FormData\\SPOTREP-2.txt';
		document.getElementById("status").innerHTML = '<h2>Upload Status</h2><img src="./images/bad.png" width="64px" />';
  console.error(err);
  		clearInterval(updateXml);
}
	
	
}
const fs = require('fs')

function runapipull() {

try {
  if (fs.existsSync('/RMS Express/'+callSign+'/FormData/SPOTREP-2.txt')) {
    //file exists
  }
} catch(err) {
  console.error(err)
}

fs.readFile('/RMS Express/'+callSign+'/FormData/SPOTREP-2.txt', 'utf8' , (err, data) => {
  if (err) {
    console.error(err)
    return
  }
if (md5(data) != lastMd) {
  var formData = new FormData();
  formData.append('spotrep', data);
  formData.append('callsign', callSign);


    // Set up the request
    var xhr = new XMLHttpRequest();

    // Open the connection
    xhr.open('POST', 'http://k9rcp-server.local.mesh/spotrep/upload.php', true);

    // Set up a handler for when the task for the request is complete
    xhr.onload = function () {
	document.getElementById("status").innerHTML = '<h2>Upload Status</h2><img src="./images/upload.png" width="64px" />';
      if (xhr.status == 200) {
        console.log('Upload copmlete!');
		document.getElementById("status-bar").innerHTML = 'Status: Last upload - '+mf("h:Ix")+' - '+memorySizeOf(data)+' - '+md5(data);
		document.getElementById("status").innerHTML = '<h2>Upload Status</h2><img src="./images/good.png" width="64px" />';
		lastMd = md5(data);
		clearInterval(updateXml);
		updateXml = setInterval( function(){ runapipull(); }, 5000 );
      } else {
        document.getElementById("status-bar").innerHTML = 'Status: Error with Status code: '+xhr.status;
		document.getElementById("status").innerHTML = '<h2>Upload Status</h2><img src="./images/bad.png" width="64px" />';
		clearInterval(updateXml);
		updateXml = setInterval( function(){ runapipull(); }, 5000 );
      }
    };
    // Send the data.
		document.getElementById("status").innerHTML = '<h2>Upload Status</h2><img src="./images/bad.png" width="64px" />';
        document.getElementById("status-bar").innerHTML = 'Status: Error Can\'t Access k9rcp-server.local.mesh';
        xhr.send(formData);

}})
}
        document.getElementById("status-bar").innerHTML = 'Please type your RMS Callsign in to Start';
</script>
  </body>

</html>