<script>
	import {Meteor} from "meteor/meteor";
	import {onMount} from "svelte";
	import {writable} from "svelte/store";
	import Select, {Option} from '@smui/select';
	import Dialog, {Title, Content, Actions} from '@smui/dialog';
	import Button, {Label} from '@smui/button';
	import List, {Item, Text, PrimaryText, SecondaryText} from '@smui/list';
	import TextField from '@smui/textfield';
	import u from 'umbrellajs';
	import {AssetTypes} from "/imports/api/asset-types";
	import Paper from '@smui/paper';

	onMount(async () => {
		Meteor.subscribe('assetTypes');
		Meteor.subscribe('assets');
	});
	let assetTypes;
	//$m: assetTypes = AssetTypes.find({}).fetch();
	//$: assetTypes = useTracker(() => AssetTypes.find({}).fetch());
	$: assetTypes = AssetTypes.find({}, {sort: {year: -1}});
	let selectedAssetTypes = [];

	let selectedType = null;
	const selectAssetType = (assetType) => {
		selectedType = assetType;
	}
	const showAddAssetType = () => {

	}
	let openAddAssetTypeButton;
	let isOpen_AddAssetType = false;
	const openAddAssetType = () => {
		isOpen_AddAssetType = !isOpen_AddAssetType;
		//openAddAssetTypeButton.innerHTML = isOpen_AddAssetType ? "close" : "add";

		if (isOpen_AddAssetType) {
			openAddAssetTypeButton.classList.add("reject-button");
		} else {
			openAddAssetTypeButton.classList.remove("reject-button");
		}
	}
	let selectedAddAssetType = null;

	let openDialog = false;
	let assetTypeDialogSelectedIndex;
	let assetTypeDialogSelectedValue;
	const openAssetTypesDialog = () => {
		assetTypeDialogSelectedIndex = -1;
		openDialog = true;
	}
	const dialogClosed = (e) => {
		switch (e.detail.action) {
			case 'accept':
				if (!selectedAssetTypes.some(e => e._id === assetTypeDialogSelectedValue._id)) {
					selectedAssetTypes = [...selectedAssetTypes, assetTypeDialogSelectedValue];
				}
				break;
			default:
			case 'cancel':
				break;
		}
	}
	let assetId = "";
	let serial = "";
	const addAsset = () => {
		if(selectedAssetType && selectedAssetType._id && assetId) {
			let result = Meteor.call("assets.add", selectedAssetType._id, assetId, serial, (err, res) => {
				if (err) {
					if (err.error === 'duplicateAssetId')
						alert("The asset ID `" + assetId + "` has already been used.");
					else
						alert(err);
				} else {
					assetId = "";
					serial = "";
					document.getElementById('assetIdField').focus();
				}
			});
		}
		else {
			if(!selectedAssetType) {
				alert("Must select an asset type.");
			}
			else {
				alert("Must provide an Asset Id.");
			}
		}
	}
	let selectedAssetType = null;
</script>

<div class="listContainer">
	<Dialog bind:open={openDialog} surface$style="width: 850px; max-width: calc(100vw - 32px);"
	        on:SMUIDialog:closed={dialogClosed}>
		<Title id="large-scroll-title">Asset Types</Title>
		<Content id="large-scroll-content">
			<List class="assetTypesList" twoLine singleSelection bind:selectedIndex={assetTypeDialogSelectedIndex}>
				{#each $assetTypes as type}
					<Item on:SMUI:action={() => (assetTypeDialogSelectedValue = type)}
					      selected={assetTypeDialogSelectedValue === type}>
						<Text>
							<PrimaryText>{type.name}</PrimaryText>
							<SecondaryText>{type.description}</SecondaryText>
						</Text>
					</Item>
				{/each}
			</List>
		</Content>
		<Actions>
			<Button action="accept" default>
				<Label>Ok</Label>
			</Button>
			<Button action="cancel">
				<Label>Cancel</Label>
			</Button>
		</Actions>
	</Dialog>

	<h3 style="display: block">Asset Types</h3>
	<Button class="addBtn" on:click={openAssetTypesDialog}>
		<Label>Add...</Label>
	</Button>
	<Paper>
		<List class="assetTypeList" singleSelection dense>
			{#each selectedAssetTypes as type}
				<Item on:SMUI:action={() => (selectedAssetType = type)} selected={selectedAssetType === type}>
					<Text>{type.name}</Text>
				</Item>
			{/each}
		</List>
	</Paper>
	<div style="grid-column: 1/span 1">
		<TextField id="assetIdField" type="text" style="width: 100%" bind:value={assetId} label="AssetId">
		</TextField>
	</div>
	<div style="grid-column: 1/span 1">
		<TextField type="text" style="width: 100%" bind:value={serial} label="Serial">
		</TextField>
	</div>
	<div style="text-align: right; margin-top: 2rem">
		<Button on:click={addAsset} variant="raised">Add</Button>
	</div>
</div>

<style>
    .columnContainer {
        display: grid;
        grid-template-columns: minmax(20rem, 1fr) minmax(20rem, 1fr);
    }

    :global(.addBtn) {
        /*margin-left: 4rem;*/
    }

    :global(.assetTypeList) {
        --mdc-ripple-color: blue;
        --mdc-ripple-selected-opacity: 0.2;
    }
    :global(.assetTypesList) {
        --mdc-ripple-selected-opacity: 0.2;
    }

    div.listContainer h2 {
        margin: 0;
    }

    .listItem:nth-child(even) {
        /*background: #f6f6f6;*/
        background: white;
    }

    .listItem {
        margin: 4px 0;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        user-select: none;
        padding-bottom: 1rem;
        padding-top: 0.4rem;
        border-bottom: 1px solid gray;
    }

    .listItem:last-child {
        border: 0;
    }

    .listItem.selected {
        background-color: rgba(255, 255, 0, 0.38);
    }
</style>