<!--
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 "extra_css"}}
<style {{- if .CSPNonce}} nonce="{{.CSPNonce}}"{{- end}}>
    .shortcut {font-family: monospace; color: #666;}
    .cm-editor {
        height: 100%;
        width: 100%;
    }

</style>
{{- end}}

{{- define "additionalnavitems"}}
<div class="d-flex align-items-center ms-2 ms-lg-3" id="kt_header_user_menu_toggle">
    <div class="btn btn-icon btn-active-light-primary w-35px h-35px w-md-40px h-md-40px" data-bs-toggle="modal" data-bs-target="#info_modal">
        <i class="ki-duotone ki-information-2 fs-2">
            <i class="path1"></i>
            <i class="path2"></i>
            <i class="path3"></i>
        </i>
    </div>
</div>
{{- end}}

{{- define "page_body"}}
{{- template "errmsg" ""}}
<div class="card shadow-sm">
    <div class="card-header">
        {{- if .ReadOnly}}
        <h6 class="card-title">View file "{{.Path}}"</h6>
        {{- else}}
        <h6 class="card-title">Edit file "{{.Path}}"</h6>
        {{- end}}
        <div class="card-toolbar">
            <a class="btn btn-light-primary px-10 me-5" href='{{.FilesURL}}?path={{.CurrentDir}}' role="button">Back</a>
            {{- if not .ReadOnly}}
            <a id="save_button" type="button" class="btn btn-primary px-10" href="#" role="button">
                <span class="indicator-label">Save</span>
			    <span class="indicator-progress">Please wait...
					<span class="spinner-border spinner-border-sm align-middle ms-2"></span>
				</span>
            </a>
            {{- end}}
        </div>
    </div>
    <div class="card-body">
        <div id="editor" class="col-sm-12 border border-light-primary"></div>
    </div>
</div>
{{- end}}

{{- define "modals"}}
<div class="modal fade" id="info_modal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">Editor keybindings</h3>
                <div class="btn btn-icon btn-sm btn-active-light-primary ms-2" data-bs-dismiss="modal" aria-label="Close">
                    <i class="ki-duotone ki-cross fs-1"><span class="path1"></span><span class="path2"></span></i>
                </div>
            </div>
            <div class="modal-body">
                <p>
                    <span class="shortcut">Ctrl-F / Cmd-F</span> => Open search panel
                </p>
                <p>
                    <span class="shortcut">Alt-G</span> => Jump to line
                </p>
                <p>
                    <span class="shortcut">Tab</span> => Indent more
                </p>
                <p>
                    <span class="shortcut">Shift-Tab</span> => Indent less
                </p>
            </div>
            <div class="modal-footer">
                <button class="btn btn-primary" type="button" data-bs-dismiss="modal">OK</button>
            </div>
        </div>
    </div>
</div>
{{- end}}

{{- define "extra_js"}}
<script {{- if .CSPNonce}} nonce="{{.CSPNonce}}"{{- end}} src="{{.StaticURL}}/vendor/codemirror/cm6.bundle.min.js"></script>
<script type="text/javascript" {{- if .CSPNonce}} nonce="{{.CSPNonce}}"{{- end}}>
    var cmView;

    function keepAlive() {
        axios.get('{{.PingURL}}',{
            timeout: 15000,
            responseType: 'text'
       	}).catch(function (error){});
    }

    //{{- if not .ReadOnly}}
    function saveFile() {
        $('#errorMsg').addClass("d-none");
        let saveButton = document.querySelector('#save_button');
	    saveButton.setAttribute('data-kt-indicator', 'on');
		saveButton.disabled = true;

        let uploadPath = '{{.FileURL}}?path='+encodeURIComponent('{{.CurrentDir}}/{{.Name}}');
        let blob = new Blob([cmView.state.doc.toString()]);

        axios.post(uploadPath, blob, {
            headers: {
                'X-CSRF-TOKEN': '{{.CSRFToken}}'
            },
            timeout: 600000,
            validateStatus: function (status) {
                    return status == 201;
                }
        }).then(function (response) {
            window.location.replace('{{.FilesURL}}?path='+encodeURIComponent('{{.CurrentDir}}'));
        }).catch(function (error) {
            saveButton.removeAttribute('data-kt-indicator');
		    saveButton.disabled = false;
            let errorMessage = "Error saving file";
            if (error && error.response) {
                if (error.response.data.message) {
                    errorMessage = error.response.data.message;
                }
                if (error.response.data.error) {
                    errorMessage += ": " + error.response.data.error;
                }
            }
            $('#errorTxt').text(errorMessage);
            $('#errorMsg').removeClass("d-none");
        });
    }
    //{{- end}}

    KTUtil.onDOMContentLoaded(function () {
        let filename = "{{.Name}}";
        let extension = filename.slice((filename.lastIndexOf(".") - 1 >>> 0) + 2).toLowerCase();
        let options = {
            oneDark: KTThemeMode.getMode() == "dark",
            fileExt: extension
        };
        //{{- if .ReadOnly}}
        options.readOnly = true;
        //{{- end}}
        //{{- if .CSPNonce}}
        options.cspNonce = "{{.CSPNonce}}";
        //{{- end}}
        let editorState = cm6.createEditorState("{{.Data}}", options);
        cmView = cm6.createEditorView(editorState, document.getElementById("editor"));

        var saveBtn = $('#save_button');
        if (saveBtn){
            saveBtn.on("click", function(){
                saveFile();
            });
        }

        setInterval(keepAlive, 300000);
    });
</script>
{{- end}}