<script context="module">
	import {
		apiEndpoints,
		site,
		locations,
		currentLocation,
		currentPhotos
	} from '../../../store'
	import { stores } from '@sapper/app'

	// Preload data
	export async function preload (page, session) {
		// Load photos
		const req = await this.fetch(`${apiEndpoints.rest}/items/photos?fields=id,name,date,slug,image.*,location.*,location.country.*,created_on,modified_on&filter[location.slug][rlike]=%${page.params.location}%&limit=-1&sort=-created_on,name`)
		const photos = await req.json()
		if (req.ok) {
			return { photos: photos.data }
		}
		this.error(404, 'Not found')
	}
</script>

<script>
	import { onMount } from 'svelte'
	const { page } = stores()

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

	// Components
	import IconGlobe from '../../../atoms/iconGlobe'
	import IconGlobeSmall from '../../../atoms/iconGlobeSmall'
	import LinkChange from '../../../atoms/LinkChange'
	import ToggleLayout from '../../../atoms/ToggleLayout'
	import Photo from '../../../molecules/Photo'
	import Switcher from '../../../molecules/Switcher'
	import Footer from '../../../molecules/Footer'

	// Props and variables
	export let photos
	let layoutSetting

	// Update current location
	const location = $locations.find(loc => loc.slug === $page.params.location)
	currentLocation.set(location)
	currentPhotos.set(photos)

	// Define dates
	$: latestPhoto = photos[0]
	$: dateUpdatedFull = latestPhoto ? dayjs(latestPhoto.modified_on).format('MMM Do, YYYY') : ''
	$: dateUpdatedDatetime = latestPhoto ?dayjs(latestPhoto.modified_on).format('YYYY-MM-DDThh:mm:ss') : ''
	$: dateUpdatedRelative = latestPhoto ?dayjs().to(dayjs(latestPhoto.modified_on)) : ''
	$: lastUpdated = latestPhoto ? (dayjs(latestPhoto.modified_on).isBefore(dayjs().subtract(1, 'M'))) ? dateUpdatedFull : dateUpdatedRelatives : ''


	/*
	** Pagination
	*/
	let photosPerPage = 2 // 12
	let currentIndex = photosPerPage
	const pagesTotal = Math.ceil(photos.length / photosPerPage)
	const pages = Array.from({ length: pagesTotal }, (v, k) => k + 1).reverse()
	let pageTranslate = 100 - (100 / pagesTotal)

	// Hide photos by default
	photos.forEach((photo, index) => photo.hidden = (index + 1 > photosPerPage) ? true : false)
	let paginatedPhotos = photos.filter(photo => photo.hidden === false)

	// Add more photos to the loop
	const displayMorePhotos = () => {
		if (currentIndex < photos.length) {
			// Display the X next hidden photos
			const photosToAppend = photos.filter(photo => photo.hidden === true).splice(0, photosPerPage)
			photosToAppend.forEach(photo => photo.hidden = false)

			// Merge new photos to show to the existing ones
			paginatedPhotos = [...paginatedPhotos, ...photosToAppend]

			// Increment current index
			currentIndex = currentIndex + photosPerPage

			// Animate the pagination
			pageTranslate = pageTranslate - (100 / pagesTotal)
		} else {
			currentIndex = photos.length
		}
	}


	/*
	** Run code on browser only
	*/
	onMount(() => {
		// Get layout setting from storage
		layoutSetting = localStorage.getItem('photosLayout')

		if (process.browser) {
			// Scroll apparitions
			AOS.init()
		}
	})
</script>

<svelte:head>
	<title>Houses Of - Beautiful houses of {location.name}, {location.country.name}</title>
</svelte:head>

<section class="place">
	<div class="place__title">
		<h1 class="title-location title-location--big">
			<span class="top">Houses <em>of</em></span>
			<span class="bottom">{location.name}</span>
		</h1>

		<a href="/choose" class="button-control button-control--big button-control--dashed">
			<span class="center">
				<IconGlobe width="44" color="#fff" />
				<span>Change</span>
			</span>
			<svg>
				<circle cx="50%" cy="50%" r="43%" />
			</svg>
		</a>
	</div>

	<div class="wrap place__description--wrap">
		<div class="place__description">
			<div class="wrapper">
				<p>{$site.description}</p>
				<p>
					Houses Of
					<LinkChange href="/choose" text={location.name}>
						<IconGlobeSmall width="14" color="#999" />
					</LinkChange>
					{location.description}
				</p>
				<p class="updated style-caps">
					<strong>Updated</strong>
					<time datetime={dateUpdatedDatetime} title={dateUpdatedFull}>{lastUpdated}</time>
				</p>

				<ToggleLayout />
			</div>
		</div>
	</div>
</section>

<section class="photos photos--{layoutSetting || 'list'}">
	<div class="photos__side--wrap wrap">
		<aside class="photos__side">
			<Switcher type="switcher--side" />
			<p class="updated style-caps">
				<strong>Updated</strong>
				<time datetime={dateUpdatedDatetime} title={dateUpdatedFull}>{lastUpdated}</time>
			</p>
		</aside>
	</div>

	{#if photos.length}
	<div class="photos__view wrap">
		{#each paginatedPhotos as photo, index}
		<Photo
			photo={photo}
			layout={layoutSetting}
			index={photos.length - (photos.indexOf(photo))}
		/>
		{/each}
	</div>

	<section class="pagination">
		{#if photos.length && currentIndex <= photos.length}
		<div class="pagination__page" class:disabled={currentIndex === photos.length}
			on:click={displayMorePhotos}
			on:mouseenter={() => pageTranslate = pageTranslate - ((100 / pagesTotal) * 0.666)}
			on:mouseleave={() => pageTranslate = pageTranslate + ((100 / pagesTotal) * 0.666)}
		>
			<div class="pagination__page--info">page</div>
			<div class="pagination__page--numbers">
				<div class="scroll" style="transform: translateY(-{pageTranslate}%);">
					{#each pages as page}
					<span>{page}</span>
					{/each}
				</div>
			</div>
			/{pagesTotal}
		</div>
		<p class="pagination__caption style-caps">See more photos</p>

		{:else}
		<div class="pagination__message">
			<h3>That's all folks!</h3>
			<p class="pagination__caption style-caps">Come back later to check out <br>new photos of {location.name}</p>
		</div>
		{/if}
	</section>
	{/if}
</section>

<Footer />
