<script>
	import {bucket_writable, counts, strings} from "../js/stores";
	import {offloadRemainingWithCount, running, tools} from "./stores";
	import Nav from "../components/Nav.svelte";
	import OffloadStatus from "../components/OffloadStatus.svelte";
	import ToolRunningStatus from "./ToolRunningStatus.svelte";
	import OffloadStatusFlyout from "../components/OffloadStatusFlyout.svelte";
	import PanelRow from "../components/PanelRow.svelte";
	import Button from "../components/Button.svelte";

	let flyoutButton;
	let expanded = false;
	let hasFocus = false;

	/**
	 * Get a message describing why the offload remaining button is disabled, if it is.
	 *
	 * @param {Object} counts
	 *
	 * @return {string}
	 */
	function getOffloadRemainingDisabledMessage( counts ) {
		if ( counts.total < 1 ) {
			return $strings.no_media;
		}

		if ( counts.not_offloaded < 1 ) {
			return $strings.all_media_offloaded;
		}

		if ( ! $bucket_writable ) {
			return $strings.disabled_tool_bucket_access;
		}

		return "";
	}

	$: offloadRemainingDisabledMessage = getOffloadRemainingDisabledMessage( $counts );

	/**
	 * Close the flyout panel and kick off the offloader.
	 *
	 * The panel is closed so that it does not pop back open without focus on completion.
	 */
	function startOffload() {
		expanded = false;
		tools.start( $tools.uploader );
	}
</script>

<Nav>
	{#if !!$running}
		<ToolRunningStatus/>
	{:else}
		<OffloadStatus bind:flyoutButton bind:expanded bind:hasFocus>
			<svelte:fragment slot="flyout">
				<OffloadStatusFlyout bind:expanded bind:hasFocus bind:buttonRef={flyoutButton}>
					<svelte:fragment slot="footer">
						<PanelRow footer class="offload-remaining">
							<Button
								primary
								disabled={offloadRemainingDisabledMessage}
								title={offloadRemainingDisabledMessage}
								on:click={startOffload}
							>
								{$offloadRemainingWithCount}
							</Button>
						</PanelRow>
					</svelte:fragment>
				</OffloadStatusFlyout>
			</svelte:fragment>
		</OffloadStatus>
	{/if}
</Nav>
