<!DOCTYPE html>
<html lang="en-US">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css"
        integrity="sha512-1ycn6IcaQQ40/MKBW2W4Rhis/DbILU74C1vSrLJxCq57o941Ym01SwNsOMqvEBFlcgUa6xLiPY/NS5R+E6ztJQ=="
        crossorigin="anonymous" referrerpolicy="no-referrer" />
    <title>FileManager</title>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14"></script>
    <script defer src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"></script>

    <script src="/filemanager-assets/dropzone.min.js"></script>
    <link href="/filemanager-assets/dropzone.min.css" rel="stylesheet" type="text/css" />

    <script src="/filemanager-assets/glightbox.min.js"></script>
    <link href="/filemanager-assets/glightbox.min.css" rel="stylesheet" type="text/css" />
    <style>
        .dz-drag-hover {
            background-color: #dbeafe;
        }
    </style>
</head>

<body>
    <div class="fixed w-full flex h-12 z-10 justify-between border-b border-gray-300 items-center px-8 bg-gray-100">
        <span class="font-bold uppercase">FileManager</span>
    </div>
    <div class="flex flex-row min-h-screen overflow-hidden pt-12 bg-gray-100 text-gray-800" x-data="filemanager">

        <!-- Include Sidebar -->
        @include 'sidebar.html'

        <main class="main flex flex-col flex-grow ml-64 transition-all duration-150 ease-in" id="dropzone-container">
            <div class="main-content relative flex flex-col flex-grow p-4">
                <div class="fixed w-full flex -ml-4 h-12 flex items-center border-b bg-gray-100 border-gray-300 -mt-4"
                    style="z-index: 1;">
                    <span class="ml-4"><em class="fa fa-search"></em></span>
                    <input type="text"
                        class="w-full bg-transparent block focus:outline-none focus:border-none px-2 text-sm"
                        placeholder="Search for files and folders" />
                </div>
                <div class="pt-12 overflow-y-hidden overflow-x-auto">
                    <div class="text-xl mb-6">All Files</div>
                    <section class="mb-10" id="folders">
                        <div class="text-xs uppercase text-gray-500 font-semibold">
                            Folders
                        </div>
                        <div class="content grid grid-cols-4 gap-4 mt-2">
                            <!-- content goes here -->
                        </div>
                    </section>
                    <section class="mb-10" id="files">
                        <div class="text-xs uppercase text-gray-500 font-semibold">
                            Files
                        </div>
                        <div class="content grid grid-cols-4 gap-4 mt-2">
                            <!-- content goes here -->
                        </div>
                    </section>
                </div>
            </div>

            <footer class="footer px-4 py-6">
                <div class="footer-content">
                    <p class="text-sm text-gray-600 text-center">
                        © Filemanager. All rights reserved.
                        <a href="">by Yubaraj Shrestha</a>
                    </p>
                </div>
            </footer>

        </main>

        <!-- Include folder-form -->
        @include 'partials/create_form.html'

        <!-- Include folder-form -->
        @include 'partials/rename_form.html'

    </div>

    <script>
        axios.interceptors.request.use(function (config) {
            const csrfToken = document.querySelector('meta[name="csrf-token"]')?.content;
            if (csrfToken) config.headers['X-CSRF-TOKEN'] = csrfToken;
            return config;
        }, function (error) {
            return Promise.reject(error);
        });

        const SetupVideoPreview = () => {
            const videos = document.getElementsByTagName("video");

            const startPreview = (video) => {
                video.muted = true;
                video.currentTime = 1;
                video.playbackRate = 0.5;
                video.play();
            }

            const stopPreview = (video) => {
                video.currentTime = 0;
                video.playbackRate = 1;
                video.pause();
            }

            const listen = (video) => {
                let previewTimeout = null;
                video.addEventListener("mouseenter", () => {
                    startPreview(video);
                    previewTimeout = setTimeout(stopPreview, 4000);
                });

                video.addEventListener("mouseleave", () => {
                    clearTimeout(previewTimeout);
                    previewTimeout = null;
                    stopPreview(video);
                });
            }

            if (videos.length) {
                for (let i = 0; i < videos.length; i++) {
                    listen(videos[i]);
                }
            }
        }

        const filemanager = {
            renameForm: {
                name: '',
                path: '',
                visibility: false,
            },
            createForm: {
                name: '',
                visibility: false,
            },
            dzone: null,
            totalSize: '0 byte',
            async init() {
                await this.fetchFilesFolders();
                SetupVideoPreview();
            },

            getEndPoints(endpoint) {
                const query = window.location.href.split("?");
                if (query.length > 1) {
                    endpoint += `?${query[1]}`;
                }
                return endpoint
            },

            async fetchFilesFolders() {
                try {
                    const response = await axios.get(this.getEndPoints('/filemanager/all-files'));
                    this.renderUI(response.data);
                    this.totalSize = response.data.total_size;
                } catch (error) {
                    console.log(error);
                }
            },

            async openFolder(folder) {
                const fullUrl = window.location.href;
                const selector = fullUrl.split("?");
                if (selector.length > 1) {
                    window.location.href = `${fullUrl},${folder}`;
                } else {
                    window.location.href = `${fullUrl}?folder=${folder}`;
                }

            },

            async openRenameForm(name, path) {
                this.renameForm = {
                    name: name,
                    path: path,
                    visibility: true,
                }
            },

            selectFile(file) {
                if (window.opener) {
                    window.opener.SetUrl(file);
                    window.close();
                }
            },

            getFileTypePreview(file) {
                let fileType = file.mime.split('/')[0];

                if (fileType == 'image') {
                    return `
						<a href="${file.url}" class="block w-full h-32 overflow-hidden bg-gray-300 rounded">
							<img src="${file.url}" class="w-full h-full object-cover">
						</a>
					`;
                }

                if (fileType == 'video') {
                    return `
						<a href="${file.url}" class="block w-full h-32 overflow-hidden bg-gray-300 rounded">
							<video class="w-full h-full object-cover">
								<source src="${file.url}" type="${file.mime}">
							</video>
						</a>
					`;
                }

                if (fileType == 'audio') {
                    return `
						<a href="${file.url}" target="_blank" class="block flex items-center justify-center w-full h-32 overflow-hidden bg-gray-300 rounded">
							<i class="fas fa-music text-4xl text-gray-600"></i>
						</a>
					`;
                }

                if (file.mime == 'application/pdf') {
                    return `
						<a href="${file.url}" target="_blank" class="block flex relative items-center justify-center w-full h-32 overflow-hidden bg-gray-300 rounded">
							<embed src="${file.url}" type="application/pdf">
							<span class="absolute w-full h-full bg-white bg-opacity-10" style="z-index: 1;"></span>
						</a>
					`;
                }

                return `
					<a href="${file.url}" target="_blank" class="block w-full h-32 overflow-hidden bg-gray-300 rounded">
						<i class="fas fa-file text-4xl text-gray-600"></i>
					</a>
				`;
            },

            getFileIcon(file) {
                let fileType = file.mime.split('/')[0];
                if (fileType == 'image') {
                    return `<i class="fas fa-file-image text-green-600"></i>`;
                }
                if (fileType == 'video') {
                    return `<i class="fas fa-video text-green-600"></i>`;
                }
                if (fileType == 'audio') {
                    return `<i class="fas fa-file-audio text-green-600"></i>`;
                }

                if (file.mime == 'application/pdf') {
                    return `<i class="fas fa-file-pdf text-green-600"></i>`;
                }
            },

            async renderUI(FileFolders) {
                let FileHtml = "";
                let FolderHtml = "";

                if (FileFolders.files.length > 0) {
                    FileFolders.files.forEach((file) => {
                        FileHtml += `
						<div class="rounded cursor-pointer relative border border-gray-300 p-1" x-on:contextmenu="$event.preventDefault(); show=true">
                            <div x-on:click.prevent="selectFile('${file.url}')">
                                ${this.getFileTypePreview(file)}
                                <div class="text-xs text-gray-500 font-semibold mt-3 overflow-ellipsis whitespace-nowrap overflow-hidden">${this.getFileIcon(file)} &nbsp; ${file.name}</div>
                                <div class="text-xs text-gray-500">${file.size}</div>
                            </div>
						</div>
					`;
                    });
                } else {
                    FileHtml = `
						<div class="text-left text-gray-500">
							<p class="text-xs mt-3">No Files Found</p>
						</div>
					`;
                }

                if (FileFolders.folders.length > 0) {
                    FileFolders.folders.forEach((folder) => {
                        FolderHtml += `
						<div x-data="{show: false}" class="rounded cursor-pointer bg-white focus:bg-gray-200 hover:shadow relative border border-gray-200 p-2 transition duration-200" x-on:contextmenu="$event.preventDefault(); show=true">
							<div class="grid grid-cols-5 gap-4 items-center" x-on:click.prevent="openFolder('${folder.name}')">
								<div class=""><em class="fas fa-folder fa-3x"></em></div>
								<div class="ml-4 relative col-span-4 flex flex-col">
									<div class="text-xs text-gray-500 font-semibold overflow-ellipsis whitespace-nowrap overflow-hidden">${folder.name}</div>
									<span class="text-xs text-gray-500">${folder.total_files} ${folder.total_files > 1 ? "files" : "file"
                            }, ${folder.size}</span>
								</div>
							</div>
						</div>
					`;
                    });
                } else {
                    FolderHtml = `
					<div class="text-left text-gray-500">
						<p class="text-xs mt-3">No Folders Found</p>
					</div>
				`;
                }

                document.querySelector("#files .content").innerHTML = FileHtml;
                document.querySelector("#folders .content").innerHTML = FolderHtml;
            }
        }
    </script>
</body>

</html>