<!--
Copyright (C) 2023 Nicola Murino

This WebUI uses the KeenThemes Mega Bundle, a proprietary theme:

https://keenthemes.com/products/templates-mega-bundle

KeenThemes HTML/CSS/JS components are allowed for use only within the
SFTPGo product and restricted to be used in a resealable HTML template
that can compete with KeenThemes products anyhow.

This WebUI is allowed for use only within the SFTPGo product and
therefore cannot be used in derivative works/products without an
explicit grant from the SFTPGo Team (support@sftpgo.com).
-->
{{- template "base" .}}

{{- define "title"}}{{.Title}}{{- end}}

{{- define "page_body"}}
<div class="d-flex flex-center flex-column flex-column-fluid p-10 pb-lg-20">
    <div class="mb-12">
        <span>
            <img alt="Logo" src="{{.StaticURL}}{{.Branding.LogoPath}}" class="h-80px" />
        </span>
        <span class="text-gray-800 fs-2 fw-semibold ps-5">
		    {{.Branding.ShortName}}
        </span>
    </div>
    <div class="card shadow-sm w-lg-600px">
        <div class="card-header bg-light">
            <h3 class="card-title text-primary">Upload one or more files to share "{{.Share.Name}}"</h3>
        </div>
        <div class="card-body">
            {{- template "errmsg" ""}}
            <form id="upload_files_form" action="{{.UploadBasePath}}" method="POST" enctype="multipart/form-data">
                <div class="fv-row">
                    <div class="dropzone" id="upload_files">
                        <div class="dz-message needsclick align-items-center">
                            <i class="ki-duotone ki-file-up fs-3x text-primary"><span class="path1"></span><span class="path2"></span></i>
                            <div class="ms-4">
                                <h3 class="fs-5 fw-bold text-gray-900 mb-1">Drop files here or click to upload.</h3>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="d-flex justify-content-end mt-10">
                    <button type="button" id="upload_files_button" class="btn btn-primary">Submit</button>
                </div>
            </form>
        </div>
    </div>
</div>
{{- end}}

{{- define "extra_js"}}
<script type="text/javascript" {{- if .CSPNonce}} nonce="{{.CSPNonce}}"{{- end}}>

    function uploadFiles(files) {
        let has_errors = false;
        let index = 0;
        let success = 0;
        $('#errorMsg').addClass("d-none");
        $('#loading_message').text("");
        KTApp.showPageLoading();

        function uploadFile() {
            if (index >= files.length || has_errors) {
                KTApp.hidePageLoading();
                if (!has_errors) {
                    ModalAlert.fire({
                        text: `File/s uploaded successfully`,
                        icon: "success",
                        confirmButtonText: "OK",
                        customClass: {
                            confirmButton: 'btn btn-primary'
                        }
                    }).then((result) => {
                        if (result.isConfirmed){
                            location.reload();
                        }
                    });
                }
                return;
            }

            let f = files[index];
            let uploadPath = '{{.UploadBasePath}}/'+encodeURIComponent(f.name);
            let lastModified;
            try {
                lastModified = f.lastModified;
            } catch (e) {
                console.log("unable to get last modified time from file: " + e.message);
                lastModified = "";
            }

            let uploadTxt = f.name;
            if (files.length > 1){
                uploadTxt = `Upload ${index+1}/${files.length}: ${uploadTxt}`;
            }

            $('#loading_message').text(uploadTxt);

            axios.post(uploadPath, f, {
                headers: {
                    'X-SFTPGO-MTIME': lastModified,
                    'X-CSRF-TOKEN': '{{.CSRFToken}}'
                },
                onUploadProgress: function (progressEvent) {
                    if (!progressEvent.total){
                        return;
                    }
                    const percentage = Math.round((100 * progressEvent.loaded) / progressEvent.total);
                    if (percentage > 0 && percentage < 100){
                        $('#loading_message').text(`${uploadTxt} ${percentage}%`);
                    }
                },
                validateStatus: function (status) {
                    return status == 201;
                }
            }).then(function (response) {
                index++;
                success++;
                uploadFile();
            }).catch(function (error) {
                let errorMessage = "Error uploading files";
                if (error && error.response) {
                    if (error.response.data.message) {
                        errorMessage = error.response.data.message;
                    }
                    if (error.response.data.error) {
                        errorMessage += ": " + error.response.data.error;
                    }
                }
                index++;
                has_errors = true;
                $('#errorTxt').text(errorMessage);
                $('#errorMsg').removeClass("d-none");
                uploadFile();
            });
        }

        uploadFile();
    }

    KTUtil.onDOMContentLoaded(function () {
        var dropzone =  new Dropzone("#upload_files", {
            url: "{{.UploadBasePath}}",
            paramName: "filenames",
            maxFiles: 200,
            maxFilesize: null,
            autoQueue: false,
            addRemoveLinks: true,
            autoProcessQueue: false,
            filesizeBase: 1000,
            init: function() {
                var dropzone = this;
                $("#upload_files_button").click(function(){
                   uploadFiles(dropzone.getAcceptedFiles());
                });
            }
        });

        dropzone.on("addedfile", file => {
            file.previewElement.querySelector(".dz-progress").style.display = 'none';
        });
    });

</script>
{{- end}}