<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <style>
            input[type=text], select {
            width: 100%;
            padding: 12px 20px;
            margin: 8px 0;
            display: inline-block;
            border: 1px solid #ccc;
            border-radius: 4px;
            box-sizing: border-box;
            }

            textarea, select {
            width: 100%;
            padding: 12px 20px;
            margin: 8px 0;
            display: inline-block;
            border: 1px solid #ccc;
            border-radius: 4px;
            box-sizing: border-box;
            }

            input[type=button] {
            width: 100%;
            background-color: #4CAF50;
            color: white;
            padding: 14px 20px;
            margin: 8px 0;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            }

            input[type=submit]:hover {
            background-color: #45a049;
            }

            table{
            width: 100%;
            }

            td{
            border-bottom: 1px solid #ccc;
            }
        </style>

        <script type="module">
        import { fromLatLon, toLatLon } from "./utm_converter.js";

        import { heightFromUTM } from "./height_from_utm.js";
        
        function findDigitGroupings(str) {
            const digitGroupings = str.match(/[\d.]+/g);
            return digitGroupings || [];
        }

        function toDMSString(decimalDegrees) {
            const degrees = Math.floor(decimalDegrees);
            const decimalMinutes = (decimalDegrees - degrees) * 60;
            const minutes = Math.floor(decimalMinutes);
            const seconds = (decimalMinutes - minutes) * 60;

            return `${degrees}° ${minutes}' ${seconds.toFixed(2)}"`;
        }
        
        function fromUnknown(str)
        {
            var lines = str.split('\n');
            let latlongs = lines.map(line => {
                let digits = findDigitGroupings(line).map(x => parseFloat(x));
                if(digits.length == 2)
                {
                    return digits
                }
                if(digits.length == 4)
                {
                    return [
                        digits[0] + (1.0/60)*digits[1],
                        digits[2] + (1.0/60)*digits[3]
                    ]
                }
                if(digits.length == 6)
                {                    
                    return [
                        digits[0] + (1.0/60)*digits[1] + (1.0/3600)*digits[2],
                        digits[3] + (1.0/60)*digits[4] + (1.0/3600)*digits[5]
                    ]
                }
                if(digits.length == 3)
                {
                    let zone = line.match(/\d\d[A-Z]/g)[0];                    
                    let res = fromUTM(digits[1],digits[2],digits[0],zone[2])
                    return [res['latitude'],res['longitude']]
                }
            });            

            
            var table_cells = latlongs.map(x => {
                let utm = fromLatLon(x[0],x[1]);
                let utmString = `${utm.zoneNum}${utm.zoneLetter} ${utm.easting.toFixed(2)} ${utm.northing.toFixed(2)}`
                let latlonString = `${x[0].toFixed(6)} N ${x[1].toFixed(6)} E`
                let dmsString = `${toDMSString(x[0])} N ${toDMSString(x[1])} E`
                return [utmString,latlonString, dmsString, heightFromUTM(utm.easting,utm.northing)]
            })
            
            table_cells = [['utm','lat/lon','lat/lon','height']].concat(table_cells)

            let resultsbox = document.getElementById("results");          
            resultsbox.replaceChildren();
            
            const table = document.createElement("table");
            for(var i=0;i < table_cells.length; i++)
            {
                const row = document.createElement("tr");
                for(var j=0;j < table_cells[i].length; j++)
                {
                    const cell = document.createElement("td");
                    const cellText = document.createTextNode(table_cells[i][j]);
                    cell.appendChild(cellText);
                    row.appendChild(cell);
                }
                table.appendChild(row);
            }
            resultsbox.appendChild(table);
        }

        document.addEventListener('DOMContentLoaded', () => {
            window.fromLatLon = fromLatLon
            window.fromUTM = toLatLon
            window.fromUnknown = fromUnknown
            window.heightFromUTM = heightFromUTM
        });
        
    </script>
    </head>
    <body>

        <form action>
            <label for="input">Enter coordinates: <span class="delicate">(one
                    per line: lat-lon (decimal degrees or not), UTM)</span></label>
            <textarea name="input" id="input" rows="4">52° 13' 46.8336'' N 21° 0' 44.0244'' E
52.229676 N 21.012229 E
34U 500835.29 5786584.44</textarea>

            <input type="button" id="convert_button" name="convert_button"
                value="Convert!"
                onclick="fromUnknown(document.getElementById('input').value)">

        </form>

        <div id="results"></div>

    </body>