<script context="module">
	// Svelte
	import { api, site, locations, currentLocation } from '../../../store'

	// Preload
	export async function preload (page, session) {
		const photos = await this.fetch(`${api.rest}/items/photos?fields=id,name,date,slug,image.data,created_on,modified_on&filter[location.slug][rlike]=%${page.params.location}%&sort=-created_on,name`)
		const photosData = await photos.json()

		return {
			photos: photosData.data
		}
	}
</script>

<script>
	// Svelte
	import { fade, slide } from 'svelte/transition'
	import { stores } from '@sapper/app'
	const { page } = stores()
	export let photos

	// Dependencies
	import dayjs from 'dayjs'
	import advancedFormat from 'dayjs/plugin/advancedFormat'
	import relativeTime from 'dayjs/plugin/relativeTime'
	dayjs.extend(advancedFormat)
	dayjs.extend(relativeTime)

	// Components
	import Photo from '../../../components/Photo.svelte'
	import SwitcherSide from '../../../components/SwitcherSide.svelte'

	// Update current location
	currentLocation.set({
		location: $locations.find(location => location.slug === $page.params.location),
		photos: photos
	})

	// Define things
	const locationFull = `${$currentLocation.location.name}, ${$currentLocation.location.country.name}`
	const dateUpdated = (photos.length) ? {
		full: dayjs(photos[0].modified_on).format('MMM Do, YYYY'),
		relative: dayjs().to(dayjs(photos[0].modified_on))
	} : undefined
	const lastUpdated = (photos.length) ? ((dayjs(photos[0].modified_on).isBefore(dayjs().subtract(1, 'M'))) ? dateUpdated.full : dateUpdated.relative) : undefined
</script>

<svelte:head>
	<title>Houses Of - Beautiful houses of {locationFull}</title>
</svelte:head>

<div class="section container" in:fade out:slide>
	<div class="nav content">
		<SwitcherSide />
	</div>

	<div class="content">
		<h1 class="title is-2">{locationFull}</h1>
		{#if $currentLocation && $currentLocation.location.description}
		<p>
			{$site.description}<br>
			Houses Of <a href="/choose">{$currentLocation.location.name}</a> {$currentLocation.location.description}
		</p>
		{/if}
		{#if photos.length > 0}
		<p><strong>Updated</strong> <time title="{dateUpdated && dateUpdated.full}">{lastUpdated}</time></p>
		{/if}
	</div>

	{#if photos.length > 0}
	<div class="columns is-multiline">
		{#each photos as photo, index}
		<div class="column is-one-third">
			<Photo {photo} index={index + 1} />
		</div>
		{/each}
	</div>
	{:else}
	<div class="message is-danger">
		<div class="message-body">
			<p>No photos for {locationFull}</p>
		</div>
	</div>
	{/if}
</div>
