<html>
    <head>
        <script src="../static/jquery-3.7.1.min.js"></script>
        <script>
            
        </script>
    </head>

    <form id="mainForm">
        URL: <input type="text" id="url" />
        Name: <input type="text" id="name" />
        <input type="submit" id="submitURLButton" title="submit" />
    </form>
    <form id="coordsForm">
        Top:<input type="text" id="top"/>
        Left:<input type="text" id="left" />
        Height:<input type="text" id="height" />
        Width:<input type="text" id="width" />
    </form>

    <div id="finalPrice"></div>

    <img src="" id="screenshot" />

    <script>
        (function (window, document, undefined) {
            
            $("#mainForm").on("submit", function(event){
                event.preventDefault();
                let url = $("#url")[0].value;
                let name = $("#name")[0].value;
                console.log(`http://localhost:8001/takeScreenshot?name=${name}&url=${url}`);
                $.ajax({
                    url: `http://localhost:8001/takeScreenshot?name=${name}&url=${url}`,
                }).done(function(){
                    $("#screenshot")[0].src = `http://localhost:8001/images/${name}.png`;
                });
                
            });

            $("#screenshot").click(function(event){
                let offset = $(this).offset();
                if($("#left")[0].value){
                    $("#height")[0].value = Math.floor((event.pageY - offset.top) - $("#top")[0].value);
                    $("#width")[0].value =  Math.floor(event.pageX - offset.left) - ($("#left")[0].value);
                    let name = $("#name")[0].value;
                    let top = $("#top")[0].value;
                    let left = $("#left")[0].value;
                    let width = $("#width")[0].value;
                    let height = $("#height")[0].value;

                    let newUrl = `http://localhost:8001/getValueFromImage?name=${name}&top=${top}&left=${left}&height=${height}&width=${width}`;
                    console.log(`${newUrl}`);
                    $.ajax({
                        url: newUrl,
                    }).done(function (response) {
                        console.log("Found Price!!!");
                        $("#finalPrice")[0].innerText = response;
                    });
                }else{
                    $("#left")[0].value = Math.floor(event.pageX - offset.left);
                    $("#top")[0].value = Math.floor(event.pageY - offset.top);
                }
                
            });

        })(this, this.document);
    </script>
</html>