<%@ control language="VB" autoeventwireup="false" inherits="Template_LargeFileUpload, MachSol.MachPanel.Web" %>

<div class="form-group">
    <div class="fileupload fileupload-new" id="FU_FileControl">
        <span class="btn btn-primary btn-file">
            <span class="fileupload-new"><%= Resources.Content.strSelectFile%></span>
            <span class="fileupload-exists"><%= Resources.Content.GN0000385%></span>
            <input type='file' id="FU_1" />
        </span>
        <input type="hidden" id="HF_FUUId" runat="server" />
        <input type="hidden" id="HF_FU_FileName" runat="server" />
        <input type="hidden" id="HF_ShowOperations" runat="server" value="1" />
        <input type="hidden" id="HF_FileExtensionsFilter" runat="server" value="" />
        <input type="hidden" id="HF_fu_complete_msg" runat="server" value="" />
        <%--<a class="btn btn-primary" href="javascript:void(0)" id="btn_file_upload">Upload file</a>--%>
    </div>
</div>

<div class="hide" id="FU_Progress">
    <div class="progress">
        <div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%">
            <span style="min-width: 2em; width: 2%"></span>
        </div>
    </div>
    <a href="javascript:void(0)" id="btn_abort_file_upload" class="btn btn-cancel">Cancel</a> &nbsp;
    <a href="javascript:void(0)" id="btn_abort_file_suspend" class="btn btn-pause btn-suspend">Suspend</a> &nbsp;
    <a href="javascript:void(0)" id="btn_abort_file_resume" class="hide btn btn-resume btn-start">Resume</a>
</div>


<div class="hide" id="FU_Completed">    
    <span id="fileupload_preview"></span>
    &nbsp;<span id="fu_complete_msg" class="alert"></span>
    &nbsp;<a href="javascript:void(0)" id="btn_abort_file_ok" onclick="resetLocals()">OK</a>
</div>

<script type="text/javascript" lang="ja">

    const CHUNK_SIZE = (1024 * 1024) * 10; //50 MB
    const CHUNK_UPLOAD_INTERVAL = 50; //in milli seconds: time delay between each upload request.

    var IsFileUploadAborted = false;
    var IsFileUploadSuspended = false;
    var SuspendPartIndex = 0;
    var baseUrl = window.location.protocol + '//' + window.location.host + '/FileUploadService.asmx';

    var uploadUrl = baseUrl + '/Upload';
    var abortUrl = baseUrl + '/Cancel';
    var sizeCheckUrl = baseUrl + '/StorageAvailableOnServer';

    function resetLocals() {
        $('#FU_FileControl').removeClass('hide');
        $('#FU_1').val('');
        $("#fu_complete_msg").html('').addClass('alert').removeClass('alert-danger').addClass('alert-success');
        $("input[id$='HF_fu_complete_msg']").first().val('');
        $('#fileupload_preview').html('');
        $('#FU_Progress').addClass('hide');
        $('#FU_Completed').addClass('hide');
        $('#btn_abort_file_suspend').removeClass('hide');
        $('#btn_abort_file_resume').addClass('hide');
        $('#FU_Progress .progress-bar').attr('style', 'width:' + 0 + '%');
        $('#FU_Progress .progress-bar span').html(0 + '%');
        SuspendPartIndex = 0;
        IsFileUploadAborted = false;
        IsFileUploadSuspended = false;
    }

    function UploadFileChunk(FileName, FileChunks, PartCount, TotalParts) {

        // file name convention  
        var Chunk = FileChunks[PartCount];
        PartCount++;
        SuspendPartIndex = PartCount;

        var FilePartName = FileName + ".part_" + PartCount + "." + TotalParts;
        var FD = new FormData();
        FD.append('file', Chunk, FilePartName);

        $.ajax(
            {
                type: "POST",
                url: uploadUrl,
                contentType: false,
                processData: false,
                data: FD,
                success: function (data) {
                    if (PartCount == TotalParts) {
                        //resetLocals();
                        $('#FU_Progress').addClass('hide');
                        $('#FU_Completed').removeClass('hide');
                        $("#fu_complete_msg").html('File uploaded successfully !').removeClass('alert-danger').addClass('alert-success');
                        $("input[id$='HF_fu_complete_msg']").first().val('File uploaded successfully !');
                    }
                    else {

                        var progressWidth = 100 / TotalParts * PartCount;
                        progressWidth = Math.floor(progressWidth);
                        $('#FU_Progress .progress-bar').attr('style', 'width:' + progressWidth + '%');
                        $('#FU_Progress .progress-bar span').html(progressWidth + '%');

                        //if not aborted and not suspended/paused then upload next chunk
                        if (!IsFileUploadAborted && !IsFileUploadSuspended) {
                            setTimeout(() => { UploadFileChunk(FileName, FileChunks, PartCount, TotalParts); }, CHUNK_UPLOAD_INTERVAL);
                        }
                        else if (IsFileUploadAborted) {
                            abortFileUpload(FileName);
                        }
                    }
                },
                error: function (error) {
                    $('#FU_Progress').addClass('hide');
                    $('#FU_Completed').removeClass('hide');
                    $("#fu_complete_msg").html('Error in uploading file. Details: ' + error.responseText).removeClass('alert-success').addClass('alert-danger');
                    $("input[id$='HF_fu_complete_msg']").first().val('Error in uploading file. Details: ' + error.responseText);
                }
            }
        );
    }

    function UploadFile(TargetFile) {

        // create array to store the buffer chunks
        var FileChunks = [];

        // the file object itself that we will work with  
        var file = TargetFile[0];

        // set up other initial vars
        var seekStartIndex = 0;

        // set the initial chunk length
        var seekEndIndex = CHUNK_SIZE;

        var Size = file.size;

        // add to the FileChunk array until we get to the end of the file  
        while (seekStartIndex < Size) {
            // "slice" the file from the starting position/offset, to  the required length  

            //file.slice(seekStartIndex, seekEndIndex).text().then(data => { console.log(data) });
            FileChunks.push(file.slice(seekStartIndex, seekEndIndex))
            seekStartIndex = seekEndIndex; // jump by the amount read  
            seekEndIndex += CHUNK_SIZE; // set next chunk index  
        }

        // get total number of "files" we will be sending  
        var TotalParts = FileChunks.length;
        var PartCount = SuspendPartIndex;

        $('#FU_FileControl').addClass('hide');
        $('#FU_Progress').removeClass('hide');

        //store client file name in hf.
        $("input[id$='HF_FU_FileName']").first().val(file.name);

        //prepend unique view id to file name for server
        var fileName = '';
        if ($("input[id$='HF_FUUId']").first().val() == null || $("input[id$='HF_FUUId']").first().val() == '')
            fileName = file.name;
        else
            fileName = $("input[id$='HF_FUUId']").first().val() + '_' + file.name;
        
        // upload the file  parts recursively in sequence
        UploadFileChunk(fileName, FileChunks, PartCount, TotalParts);

    }

    function abortFileUpload(fileName) {
        $.ajax(
            {
                type: "POST",
                url: abortUrl,
                data: { 'fileName': fileName },
                success: function (data) {
                    resetLocals();
                },
                error: function (error) { resetLocals(); console.error(error.responseText); }
            }
        );
    }

    function checkSizeAndUpload($fileSrc) {
        var targetFile = $fileSrc[0].files[0];
        $.ajax(
            {
                type: "POST",
                url: sizeCheckUrl,
                data: { 'fileSize': targetFile.size },
                success: function (data) {
                    hideOperationsIfRequired();
                    var fileValidated = false;

                    if ($("input[id$='HF_FileExtensionsFilter']").first().val() != "") {
                        const lastDot = targetFile.name.lastIndexOf('.');
                        const ext = targetFile.name.substring(lastDot + 1);
                        var a = $("input[id$='HF_FileExtensionsFilter']").first().val().split(",");
                        var i = 0;                        

                        for (i = 0; i < a.length; i++) {
                            if (a[i] == ext) {
                                fileValidated = true;
                                break;
                            }
                        }
                    }
                    else
                        fileValidated = true;

                    if (fileValidated) {
                        UploadFile($fileSrc[0].files);
                        $('#fileupload_preview').html(targetFile.name);
                    }
                    else {
                        $('#FU_Progress').addClass('hide');
                        $('#FU_Completed').removeClass('hide');
                        $('#fileupload_preview').html('');
                        $("#fu_complete_msg").html('Valid file extensions are: ' + $("input[id$='HF_FileExtensionsFilter']").first().val()).removeClass('alert-success').addClass('alert-danger');
                        $("input[id$='HF_fu_complete_msg']").first().val('Valid file extensions are: ' + $("input[id$='HF_FileExtensionsFilter']").first().val());
                    }
                },
                error: function (error) {
                    hideOperationsIfRequired();
                    $('#FU_Progress').addClass('hide');
                    $('#FU_Completed').removeClass('hide');
                    $('#fileupload_preview').html('');
                    $("#fu_complete_msg").html(error.responseText).removeClass('alert-success').addClass('alert-danger');
                    $("input[id$='HF_fu_complete_msg']").first().val(error.responseText);
                }
            }
        );
    }

    function hideOperationsIfRequired() {        
        if ($("input[id$='HF_ShowOperations']").first().val() != "1") {
            $('#btn_abort_file_ok').addClass('hide');
            $('#btn_abort_file_upload').addClass('hide');
            $('#btn_abort_file_suspend').addClass('hide');
            $('#btn_abort_file_resume').addClass('hide');
        }
    }

    $(document).ready(function () {

        $('#FU_1').change(function () {
            checkSizeAndUpload($(this));
        });

        //$('#btn_file_upload').click(function () {
        //    UploadFile($('#FU_1')[0].files);
        //}
        //);
        $('#btn_abort_file_upload').click(function () {
            if (!IsFileUploadSuspended)
                IsFileUploadAborted = true;
            else {
                if ($("input[id$='HF_FUUId']").first().val() == null || $("input[id$='HF_FUUId']").first().val() == '')
                    abortFileUpload($('#FU_1')[0].files[0].name);
                else
                    abortFileUpload($("input[id$='HF_FUUId']").first().val() + '_' + $('#FU_1')[0].files[0].name);
            }
        });

        $('#btn_abort_file_suspend').click(function () {
            IsFileUploadSuspended = true;
            $('#btn_abort_file_resume').removeClass('hide');
            $(this).addClass('hide');
        });

        $('#btn_abort_file_resume').click(function () {
            IsFileUploadSuspended = false;
            $('#btn_abort_file_suspend').removeClass('hide');
            $(this).addClass('hide');
            UploadFile($('#FU_1')[0].files); //resume file upload
        });

    });

</script>
