@using SharpConnector.Constants;
@using System.Configuration;
@{
    Layout = "~/Views/Shared/_Layout_NoSideNav.cshtml";
}
<div class="inner_wrapper half-center">
    <h1>Scanning in progress...</h1>
    <p id="status"></p>
</div>

@section Scripts {
    <script>
        var _mfpApi = '@ConfigurationManager.AppSettings["MFP:apiUrl"]';
        var _mfpVer = '@ConfigurationManager.AppSettings["MFP:apiVersion"]';
        var projectUrl = '@ConfigurationManager.AppSettings["MFP:projectUrl"]';

        var JobId;
        var Status;
        var Description;

        ExecuteScanJob();

        function ExecuteScanJob() {
            
            var fileFormat = '@HttpUtility.JavaScriptStringEncode(string.IsNullOrEmpty(ConfigurationManager.AppSettings["File:format"]) ? "pdf" : ConfigurationManager.AppSettings["File:format"])';
            var colorMode  = '@HttpUtility.JavaScriptStringEncode(string.IsNullOrEmpty(ConfigurationManager.AppSettings["Scan:colorMode"]) ? "monochrome" : ConfigurationManager.AppSettings["Scan:colorMode"])';

            var fileName = '@(HttpContext.Current.Session[MFP.FileName].ToString())';
            fileName = fileName.split('.')[0]; /* Get file name without extension */

            var reqStr = _mfpApi + 'mfpscan/ExecuteJob/' + _mfpVer + '?res=jsonp&callback=errorCheckFunc';
            reqStr += '&vkey=' + '@HttpUtility.UrlEncode(HttpContext.Current.Session[MFP.APIKey].ToString())';
            reqStr += '&ColorMode=' + colorMode;
            reqStr += '&FileFormat=' + fileFormat;
            reqStr += '&TransferProtocol=http';
            reqStr += '&HttpResult=true';
            reqStr += '&FileName=' + fileName;
            reqStr += '&HttpUrl=' + projectUrl + 'Mfp/UploadFile';

            mfpLog("ScanExecuteJobRequest", encodeURIComponent(reqStr));

            jsonpRequest(reqStr, "ExecuteJobCallback");
        }

        // ------------------------------------------------------------------------------
        function ExecuteJobCallback(_retParam) {
            var exeJobResponse = JSON.stringify(_retParam["result"]["ExecuteJobResponse"], null, " ");
            mfpLog("ScanExecuteJobResponse", exeJobResponse);

            JobId = _retParam["result"]["ExecuteJobResponse"]["jobId"];
            Status = "none";
            document.getElementById("status").innerHTML = "JOB STATUS = " + Status;            
            callGetJobStatus();
        }

        // ------------------------------------------------------------------------------
        // job status polling.
        function callGetJobStatus() {
            var reqStr = _mfpApi + "mfpscan/GetJobStatus/" + _mfpVer + "?res=jsonp&callback=errorCheckFunc&JobId=" + JobId;
            jsonpRequest(reqStr, "GetJobStatusCallback");
        }

        // ------------------------------------------------------------------------------
        function GetJobStatusCallback(_retParam) {
            // check current job status 
            if (Status != _retParam["result"]["GetJobStatusResponse"]["status"]) {
                Status = _retParam["result"]["GetJobStatusResponse"]["status"];
                Description = _retParam["result"]["GetJobStatusResponse"]["Description"];
                document.getElementById("status").innerHTML = "JOB STATUS = " + Status
                    + (Status == "FINISHED" ? ', @Msg.SendingMessage' : '');
            }

            // Check whether the current job has been finished.
            if (Status != "FINISHED" && Status != "CANCELED" && Status != "ERROR") {

                // If the current job is still running, continue status polling.
                setTimeout(callGetJobStatus, 1000);
            }
            else if (Status == "CANCELED") {
                navigateTo('@Url.Action("Index", "Home", new { message = Msg.ScanCancelled } )');
            }
            else if (Status == "ERROR") {
                navigateTo('@Url.Action("Index", "Home", new { message = Msg.FailedScan })');
            }
            else {    
                var attempts = @Int16.Parse(ConfigurationManager.AppSettings["File:searchAttempts"]);
                var interval = @Int16.Parse(ConfigurationManager.AppSettings["File:searchInterval"]);

                var ticks = 1;
                var intervalID = setInterval(function () {
                    if (ticks > attempts) {
                        clearInterval(intervalID);
                    }
                    else {
                        CheckJobStatus();
                    }
                    ticks++;

                }, interval * 1000);
            }
        }
        // ------------------------------------------------------------------------------

        function CheckJobStatus() {
            var url = '@Url.Action("CheckStatus", "Mfp")';

            ExecuteReq('GET', url, null, function (data) {
                var dataArr = data.split('|');
                var status = dataArr[0];
                var message = dataArr[1];

                switch (status) {
                    case '@SharpConnector.Models.Enums.Status.Success.ToString()':
                        window.location.href = '@Url.Action("Success", "Home")';
                        break;
                    case '@SharpConnector.Models.Enums.Status.Error.ToString()':
                        window.location.href = '@Url.Action("Index", "Home")' + '?message=' + message;
                        break;
                    case '@SharpConnector.Models.Enums.Status.InProgress.ToString()':
                    default:
                        break;
                }
            });
        }
    </script>
}
