<%inherit file="/base/base.mako"/>

<%def name="title()">
    ${_('{} Files Upload').format(c.repo_name)}
    %if c.rhodecode_name:
        &middot; ${h.branding(c.rhodecode_name)}
    %endif
</%def>

<%def name="menu_bar_nav()">
    ${self.menu_items(active='repositories')}
</%def>

<%def name="breadcrumbs_links()"></%def>

<%def name="menu_bar_subnav()">
    ${self.repo_menu(active='files')}
</%def>

<%def name="main()">

<div class="box">
    ## Template for uploads
    <div class="edit-file-title">
        % if c.replace_binary:
            <span class="title-heading">${_('Replace content of')} <b>${c.f_path}</b> </code></span>
        % else:
            <span class="title-heading">${_('Upload new file')} </span>
        % endif
        % for branch in c.commit.branches:
        <span class="tag branchtag">
            <i class="icon-branch"></i> ${branch}
        </span>
        % endfor
    </div>

    % if not c.replace_binary:
        <% form_url = h.route_path('repo_files_upload_file', repo_name=c.repo_name, commit_id=c.commit.raw_id, f_path=c.f_path) %>
        <div class="edit-file-fieldset">
            <div class="path-items">
                <ul class="tooltip" title="Repository path to store uploaded files. To change it, navigate to different path and click upload from there.">
                <li class="breadcrumb-path">
                    <div>
                        <a href="${h.route_path('repo_files', repo_name=c.repo_name, commit_id=c.commit.raw_id, f_path='')}"><i class="icon-home"></i></a> /
                        <a href="${h.route_path('repo_files', repo_name=c.repo_name, commit_id=c.commit.raw_id, f_path=c.f_path)}">${c.f_path}</a>${('/' if c.f_path else '')}
                    </div>
                </li>
                <li class="location-path">

                </li>
                </ul>
            </div>

        </div>
    % else:
        <% form_url = h.route_path('repo_files_replace_binary', repo_name=c.repo_name, commit_id=c.commit.raw_id, f_path=c.f_path) %>
    % endif

    <div class="upload-form table">
        <div>
            <div class="filepond-wrapper" style="border: none; padding: 40px 0">
                <input type="file"
                       id="file-uploader"
                       name="files_upload"
                       multiple
                />
            </div>
        </div>
    </div>

    <div class="upload-form edit-file-fieldset">
        <div class="fieldset">
            <div class="message">
                <textarea id="commit" name="message"  placeholder="${c.default_message}"></textarea>
            </div>
        </div>
        <div class="pull-left">
            ${h.submit('commit_btn',_('Commit changes'), class_="btn btn-small btn-success")}
        </div>
    </div>

    <div class="file-upload-transaction-wrapper" style="display: none">
        <div class="file-upload-transaction">
            <h3>${_('Committing...')}</h3>
            <p>${_('Please wait while the files are being uploaded')}</p>
            <p class="error" style="display: none"></p>
            <i class="icon-spin animate-spin"></i>
            <p></p>
        </div>
    </div>

</div>

<script type="text/javascript">
    $(document).ready(function () {

        // Create FilePond instance
        const inputElement = document.querySelector('#file-uploader');

        const labelIdleHtml = `
            <i class="icon-upload" style="font-size:36px"></i><br/>
            % if not c.replace_binary:
                ${_("Drag'n Drop files here or")} <span class="link">${_('Choose your files')}</span>.<br>
            % else:
                ${_("Drag'n Drop file here or")} <span class="link">${_('Choose your file')}</span>.<br>
            % endif
        `;

        const pond = FilePond.create(inputElement, {
            allowMultiple: true,
            maxFiles: 20,
            instantUpload: false,
            credits: false,
            allowFileMetadata: false,
            labelIdle: labelIdleHtml,

            server: {
                process: {
                    url: "${form_url}",
                    method: "POST",
                    withCredentials: false,
                    headers: {
                        "X-CSRF-Token": CSRF_TOKEN
                    },
                    ondata: function (formData) {
                        formData.append("message", $('#commit').val());
                        return formData;
                    },
                    onload: function (responseText) {
                        let response = null;
                        try {
                            response = JSON.parse(responseText);
                        } catch (e) {
                            console.error("Invalid JSON response from upload", e, responseText);
                            return null;
                        }

                        if (response.error !== null && response.error !== undefined) {
                            $('.file-upload-transaction-wrapper .error').html(
                                'ERROR: {0}'.format(response.error)
                            );
                            $('.file-upload-transaction-wrapper .error').show();
                            $('.file-upload-transaction-wrapper i').hide();
                        }

                        let redirect_url = response.redirect_url || '/';
                        window.location = redirect_url;

                        return response.file_id || null;
                    },
                    onerror: function (responseText) {
                        let error = 'Upload error';
                        try {
                            let data = JSON.parse(responseText);
                            if (data && data.error) {
                                error = data.error;
                            }
                        } catch (e) {
                            // response not JSON, ignore
                        }

                        $('.file-upload-transaction-wrapper .error').html(
                            'ERROR: {0}'.format(error)
                        );
                        $('.file-upload-transaction-wrapper .error').show();
                        $('.file-upload-transaction-wrapper i').hide();

                        return error;
                    }
                }
            }
        });

        $('#commit_btn').on('click', function (e) {
            e.preventDefault();

            let button = $(this);
            if (button.hasClass('clicked')) {
                button.attr('disabled', true);
            } else {
                button.addClass('clicked');
            }

            let files = pond.getFiles();
            if (files.length === 0) {
                alert("Missing files");
                // reset button state to allow retry
                button.removeClass('clicked').attr('disabled', false);
                return;
            }

            $('.upload-form').hide();
            $('.file-upload-transaction-wrapper').show();

            // start uploading all files in the pond
            pond.processFiles();
        });

    });
</script>
</%def>
