<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" type="text/css" href="static/styles.css">
        <title> Rupee to Dollar </title>
    
        <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/emailjs-com@2.3.2/dist/email.min.js"></script>
        <script type="text/javascript">
            (function(){
            emailjs.init("<YOUR_EMAIL_KEY>");
            })();
        </script>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/5.0.2/papaparse.js"></script>
        <script src= "static/table_format_convert.js"></script>

    </head>
    
    <body><br>
    <h2> Rupee to Dollar Converter </h2>
    <br>
    
    <form class="form-inline">
        <input class="input input1" id="fileupload" name="myfile" type="file" accept=".csv" required/>
        <button class="button button1" type="submit" id="submit-file"> Upload CSV </button>
    </form>
    
    <br><br>
    <div id = "converted_table"></div>

    <br>
    <form id="send_mail">
        <input class="input inputemail" id = "email" type="text" placeholder="Email_ID" required>
        <tab2><button class="button button1" onclick="send_email()" type="submit" id="submit" > Submit </button></tab2>
    </form>
    </body>
</html>

<script type="text/javascript">
var table;
var converted_csv;
var dollar_rate;
var timestamp;
var csv_list = new Array();

fetch('http://api.currencylayer.com/live?access_key=<YOUR_CURRENCYAPI_KEY>')
    .then(response => response.json())
    .then(function(response) {
        console.log(response)
        dollar_rate = response.quotes.USDINR;
        timestamp = response.timestamp;           // unix timestamp is stored
    })
    .catch(error => console.error(error));

$(document).ready(function(){

    $('#submit-file').on("click",function(e){
		e.preventDefault();
		$('#fileupload').parse({
		config: {
			delimiter: "auto",
			complete: displayHTMLTable,
		},
		before: function(file, inputElem)
		{
		},
		error: function(err, file)
		{
            console.log("CSV file is in incorrect format")
		},
		complete: function()
		{
			console.log("Done with all files");
		}
        });
    });

    function displayHTMLTable(results){
        var table = "Converted USD Table<br><br><table class='table table-dark'>";
        var data = results.data;
        csv_list = [];
        for(i=0;i<data.length;i++){
            table+= "<tr>";
            var row = data[i];
            var cells = row.join(",").split(",");
            
            for(j=0;j<cells.length;j++){
                table+= "<td>$";
                table+= (Number(cells[j])/dollar_rate).toFixed(3);
                converted_csv += String((Number(cells[j])/dollar_rate).toFixed(3)) + ", ";
                csv_list.push((Number(cells[j])/dollar_rate).toFixed(3))
                table+= "</th>";
            }
            table+= "</tr>";
            converted_csv += "\n"
        }
        table+= "</table>";
        table += ("<br><p> Dollar Rate : "+ dollar_rate +"<tab2>");
        time_stamp = new Date(timestamp*1000).toLocaleTimeString("en-IN") + "  " + new Date(timestamp*1000).toLocaleDateString("en-IN")
        table += ("Fetching time : "+ time_stamp);
        table += "</tab2><br><br>Min : " + String(Math.min(...csv_list));
        table += "<tab2>Max : " + String(Math.max(...csv_list));
        
        var total=0;
        for(var i in csv_list) { total += Number(csv_list[i]); }
        
        table += "</tab2><tab2>Avg : " + String((total / csv_list.length).toFixed(2)) + "</tab2>";
        $("#converted_table").html(table);
    };
  });

function send_email(){
    var param = { email : document.querySelector('#email').value, converted : converted_csv };
    emailjs.send('gmail', 'send_converted_csv', param);
    alert("Mail has been sent successfully to your email id.")
};
</script>
