<template>
	<div>
		<div class="d-flex align-items-center justify-content-between">
			<h5>مدیریت فایل ها</h5>
			<div class="d-flex">
				<div id="upload-files" class="form-group m-form__group my-0 ml-2">
					<div></div>
					<div class="custom-file">
						<input
							type="file"
							class="custom-file-input"
							multiple
							@change="processFile($event)"
						/>
						<label class="custom-file-label text-center"></label>
					</div>
				</div>
				<b-button variant="info" class="ml-2" @click="$refs.modal.show()"
					>ایجاد پوشه</b-button
				>
			</div>
		</div>
		<hr />
		<div class="row">
			<div class="col-md-9">
				<nav class="mb-4 d-flex">
					<ol class="breadcrumb m-0 bg-white flex-fill">
						<li class="breadcrumb-item">
							<span @click="changeDirectory(-1)">خانه</span>
						</li>
						<li
							v-for="(path, index) in list"
							:key="index"
							class="breadcrumb-item"
						>
							<span @click="changeDirectory(index)">{{ path }}</span>
						</li>
					</ol>
					<button
						type="button"
						class="btn btn-sm btn-secondary"
						@click="
							items.home &&
								changeDirectory(
									(items.home.match(new RegExp('/', 'g')) || []).length - 1
								)
						"
					>
						<i class="la la-arrow-up fa-2x"></i>
					</button>
				</nav>
				<div class="d-flex flex-wrap">
					<item
						v-for="(item, index) in items.data"
						:key="index"
						:class="
							selectable === 'multiple' && {
								selected: value.includes(item.url)
							}
						"
						:item="item"
						@dblclick="openItem(index)"
						@click="selectItem(index)"
					/>
				</div>
			</div>
			<div class="col-md-3 border-left">
				<item-preview
					:item="infoItem != null && items.data[infoItem]"
					@delete="deleteItem"
				/>
			</div>
		</div>
		<b-modal ref="modal" title="ایجاد پوشه">
			<div class="m-form">
				<div class="form-group m-form__group">
					<b-form-group label="نام پوشه" label-for="input-1">
						<b-form-input id="input-1" v-model="directory.name" />
					</b-form-group>
					<form-input
						id="item-title"
						v-model="directory.name"
						name="title"
						label="نام پوشه"
					/>
					<b-form-input v-model="directory.name"></b-form-input>
				</div>
			</div>
			<template v-slot:modal-footer="{ ok, cancel, hide }">
				<b-button variant="info" @click="createDirectory(ok)"
					>ایجاد پوشه</b-button
				>
				<b-button @click="cancel">بستن</b-button>
			</template>
		</b-modal>
	</div>
</template>

<script>
import Item from "./components/Item";
import ItemPreview from "./components/ItemPreview";

export default {
	name: "FileManager",
	components: {
		Item,
		ItemPreview
	},
	components: { ItemPreview, Item },
	props: {
		value: {
			type: Array,
			default: () => []
		},
		selectable: {
			default: false,
			validator: val => [false, true, "multiple"].includes(val)
		}
	},
	data() {
		return {
			items: {},
			infoItem: null,
			directory: {
				name: null
			}
		};
	},
	computed: {
		list() {
			return this.items.home ? this.items.home.split("/") : [];
		}
	},
	created() {
		this.$axios
			.$post("/api/media")
			.then(data => (this.items = data))
			.finally(() => (this.items.data = _.sortBy(this.items.data, "type")));
	},
	methods: {
		changeDirectory(level) {
			let directory = "";
			for (let i = 0; i <= level; i++) directory += this.list[i] + "/";

			const req = { directory: directory.slice(0, -1) };
			this.$axios.$post("/api/media", req).then(data => (this.items = data));
		},
		createDirectory(handler) {
			const req = { directory: this.items.home, name: this.directory.name };
			this.$axios
				.$post("/api/media/create", req)
				.then(data => this.items.data.push(data))
				.finally(() => {
					handler();
					this.items.data = _.sortBy(this.items.data, "type");
				});
		},

		uploadFiles(name, data) {
			this.$axios
				.$post("/api/media/upload", {
					image: { name, data },
					directory: this.items.home
				})
				.then(data => this.items.data.push(data.data));
		},
		processFile(event) {
			for (const file in event.target.files) {
				if (typeof event.target.files[file] === "number") break;
				const reader = new FileReader();
				const fileName = event.target.files[file].name;
				reader.readAsDataURL(event.target.files[file]);
				reader.onload = () => this.uploadFiles(fileName, reader.result);
			}
		},
		deleteItem() {
			if (confirm("آیا مایل به حذف هستید ؟")) {
				const itemID = this.infoItem;
				this.infoItem = null;
				const req = {
					directory: this.items.home,
					name: this.items.data[itemID].name
				};
				this.$axios
					.$post("/api/media/delete", req)
					.then(() => this.items.data.splice(itemID, 1));
			}
		},
		selectItem(index) {
			this.infoItem = index;
			if (this.selectable) {
				if (this.items.data[index].type === "dir") return;
				if (this.selectable === true) {
					this.value = this.items.data[index].url;
				} else if (this.selectable === "multiple") {
					const itemIndex = this.value.findIndex(
						item => item === this.items.data[index].url
					);
					itemIndex === -1
						? this.value.push(this.items.data[index].url)
						: this.value.splice(itemIndex, 1);
				}
				this.$emit("input", this.value);
			}
		},
		openItem(index) {
			if (this.items.data[index].type === "dir") {
				this.infoItem = null;
				this.$axios
					.$post("/api/media", { directory: this.items.data[index].directory })
					.then(data => (this.items = data));
			}
		}
	}
};
</script>

<style lang="scss" scoped>
#upload-files {
	width: 8rem;

	* {
		cursor: pointer;
	}

	.custom-file-label:after {
		width: 100%;
		cursor: pointer;
		border-right: none;
		content: "آپلود فایل";
	}
}

.breadcrumb {
	span {
		opacity: 0.7;
		cursor: pointer;

		&:hover {
			opacity: 1;
		}
	}
}
</style>
