<script lang="ts">
    import {locals} from "../ts/stores.js";
    import {route} from "../../common/Routing";
    import BaseTemplate from "./templates/BaseTemplate.svelte";
    import Form from "./utils/Form.svelte";
    import Field from "./utils/Field.svelte";
    import CopyableText from "./components/CopyableText.svelte";
    import Pagination from "./components/Pagination.svelte";
    import Message from "./components/Message.svelte";
    import Icon from "./utils/Icon.svelte"
    import FileUpload from "./components/FileUpload.svelte";

    let neverExpire: string;
    let autogenUrl: string;

    let uploadForm: HTMLFormElement;
    let selectedFiles: FileList | undefined;
    let nextFileIndex = 0;
    let uploading: boolean = false;
    let currentFile: File | undefined;

    let finishedFileUploads: { name: string, finalUrl: string }[] = [];

    function uploadFiles(e) {
        e.preventDefault();
        uploadForm = this;

        if (selectedFiles && !uploading) {
            processNextUpload();
        }
    }

    async function processNextUpload() {
        if (nextFileIndex > selectedFiles.length - 1) {
            nextFileIndex = 0;
            selectedFiles = undefined;
            uploading = false;
            return;
        }
        uploading = true;
        currentFile = selectedFiles[nextFileIndex++];
    }

    function onUploadEnd(fileName, finalUrl) {
        if (finalUrl) {
            finishedFileUploads = [...finishedFileUploads, {name: fileName, finalUrl: finalUrl}];
        }
        processNextUpload();
    }
</script>

<style lang="scss">
	.file-upload-table {
		@media (max-width: 550px) {
			> thead > tr > th:nth-child(3),
			> tbody > tr > td:nth-child(3) {
				display: none;
			}
		}

		@media (max-width: 785px) {
			> thead > tr > th:nth-child(4),
			> tbody > tr > td:nth-child(4) {
				display: none;
			}
		}
	}

	.actions {
		display: flex;
		flex-direction: row;

		:global(button .icon) {
			margin: 0 !important;
		}

		:global(button .tip) {
			display: none;
		}
	}
</style>

<BaseTemplate title="{$locals.app.name} - Upload file" description="File upload web interface." noH1>
    <h1>Upload files</h1>

    <div class="container">
        <section class="panel">
            <h2>
                <Icon name="upload"/>
                Upload files
            </h2>
            <p>You are responsible for the files that you upload.</p>

            {#each finishedFileUploads as fileUpload}
                <CopyableText title="{fileUpload.name}" content="{fileUpload.finalUrl}"/>
            {/each}

            {#if uploading}
                <FileUpload file={currentFile} form={uploadForm} fileFieldName="upload"
                            onEnd={onUploadEnd} autostart/>
            {:else}
                <Form action={route('post-file-frontend')} withFiles
                      submitText="Upload" submitIcon="upload"
                      onSubmit={uploadFiles}>
                    <Field type="file" name="upload" placeholder="Choose wisely" icon="file"
                           hint="The maximum upload size is {$locals.max_upload_size} MiB"
                           multiple required
                           bind:fileList={selectedFiles}/>

                    <Field type="checkbox" name="never_expire" placeholder="Never delete this file"
                           icon="infinity"
                           bind:value={neverExpire}/>
                    {#if !neverExpire}
                        <Field type="number" name="expire_after_days" icon="clock"
                               placeholder="How many days to delete this file after"
                               initialValue={30} max="1825"/>
                    {/if}

                    {#if !selectedFiles || selectedFiles.length <= 1}
                        <Field type="checkbox" name="autogen_url" placeholder="Generate url automatically"
                               icon="zap"
                               bind:value={autogenUrl} initialValue={true}/>
                        {#if !autogenUrl}
                            <Field type="text" name="slug" placeholder="Custom url slug" icon="link"
                                   hint="Example: beautiful_image.jpg sets url to https://{$locals.default_domain}/beautiful_image.jpg"/>
                        {/if}
                    {:else}
                        <Message type="info" discreet sticky
                                 content="When upload multiple files, URLs will be generated automatically."/>
                    {/if}
                </Form>
            {/if}

            {#if $locals.flash.url}
                <CopyableText title="URL" content={$locals.flash.url}/>
            {/if}
        </section>


        <section class="panel">
            <h2>
                <Icon name="folder"/>
                File list
            </h2>

            <Pagination pagination={$locals.pagination} routeName="file-uploader" contextSize={3}/>

            <div class="data-table-container">
                <table class="data-table file-upload-table">
                    <thead>
                    <tr>
                        <th>#</th>
                        <th class="table-col-grow">Name</th>
                        <th>Size</th>
                        <th>Expires at</th>
                        <th>Actions</th>
                    </tr>
                    </thead>

                    <tbody>
                    {#each $locals.files as file}
                        <tr>
                            <td>{file.id}</td>
                            <td class="table-col-grow-cell"><a href="{file.url}">
                                <pre>{file.real_name}</pre>
                            </a></td>
                            <td>{(file.size / (1024 * 1024)).toFixed(2)}MB</td>
                            <td>
                                {#if file.expires_at}{file.expires_at}{:else}Never{/if}
                            </td><!-- todo: convert that to relative, human readable time -->
                            <td class="actions">
                                {#if file.shouldBeDeleted}
                                    Pending deletion
                                {:else}
                                    <button class="copy-button" data-content="{file.url}">
                                        <Icon name="copy"/>
                                        <span class="tip">Copy URL</span></button><!-- todo -->

                                    <Form action={route('delete-file-frontend', file.slug)} button
                                          submitIcon="trash" submitText="delete" submitClass="danger"
                                          confirm="Are you sure you want to delete file {file.real_name}?"/>
                                {/if}
                            </td>
                        </tr>
                    {:else}
                        <tr>
                            <td colspan="5" class="center">You haven't uploaded any file yet.</td>
                        </tr>
                    {/each}
                    </tbody>
                </table>
            </div>

            <Pagination pagination={$locals.pagination} routeName="file-uploader" contextSize={3}/>
        </section>
    </div>
</BaseTemplate>
