<script>
    import { onMount } from 'svelte'
    import { currentLocation } from '../store'
    import * as fn from '../functions'

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

    // Components
    import IconArrow from '../atoms/IconArrow'

    // Props
    export let viewer = false
    export let photos = []

    // Variables
    let hover
    let currentIndex = 1
    $: currentPhoto = photos[currentIndex] || null
    $: prevPhoto = photos[currentIndex - 1] || photos[photos.length - 1]
    $: nextPhoto = photos[currentIndex + 1] || photos[0]


    /*
    ** Go to a photo
    */
    const goToPrev = () => {
        currentIndex--
        currentIndex = (currentIndex < 0) ? photos.length - 1 : currentIndex
    }
    const goToNext = () => {
        currentIndex++
        currentIndex = (currentIndex >= photos.length) ? 0 : currentIndex
    }


    /*
    ** Drag and touch navigation
    */
    let touchStartX = 0
    let touchStartY = 0
    let touchEndX = 0
    let touchEndY = 0

    const swipeStart = event => {
        touchStartX = event.changedTouches[0].screenX
        touchStartY = event.changedTouches[0].screenY
    }
    const swipeEnd = event => {
        touchEndX = event.changedTouches[0].screenX
        touchEndY = event.changedTouches[0].screenY
        if (touchEndX <= touchStartX) goToNext()
        if (touchEndX >= touchStartX) goToPrev()
    }

    // Keyboard navigation
    const keyboardNav = event => {
        const keyCode = event.keyCode

        switch (event.keyCode) {
            case 37: case 80: case 74:
                goToPrev()
                break
            case 39: case 78: case 75:
                goToNext()
                break
            // case 27: case 67:
            //     document.getElementById('photo_close').click()
            //     break
            default: break
        }
    }


    /*
    ** Run code on browser only
    */
    onMount(() => {
        // Hover function
        hover = event => {
            const button = event.currentTarget.querySelector('button')
            const photoActive = document.querySelector('.gallery__images .active')

            let photoToHover
            if (event.currentTarget.dataset.to === 'prev') {
                photoToHover = (photoActive.previousSibling != null) ? photoActive.previousSibling : photoActive.parentNode.lastChild
            } else {
                photoToHover = (photoActive.nextSibling != null) ? photoActive.nextSibling : photoActive.parentNode.firstChild
            }

            switch (event.type) {
                case 'mouseenter':
                    photoToHover.classList.add('hover')
                    button.focus()
                    break
                case 'mouseleave':
                    photoToHover.classList.remove('hover')
                    button.blur()
                    break
                default: break
            }
        }
    })

    /*
        REVEAL ANIMATION ON CAROUSEL:
        Fix the CSS priority? Cancel the transition delay and duration?
        data-aos="{
            (photo === prevPhoto) ? 'carousel-prev' :
            (photo === currentPhoto) ? 'carousel-active' :
            (photo === nextPhoto) ? 'carousel-next' : ''
        }
    */
</script>

<svelte:window on:keydown={keyboardNav} />

<div class="carousel" on:touchstart={swipeStart} on:touchend={swipeEnd}>
    <div class="wrap">
        <div class="gallery">
            <div class="gallery__images">
                {#each photos as photo, index}
                <picture class="gallery__images--photo"
                    class:prev={photo === prevPhoto}
                    class:active={photo === currentPhoto}
                    class:next={photo === nextPhoto}
                >
                    <source media="(min-width: 968px)" srcset={fn.getThumbnail(photo.image.private_hash, 1400)}>
                    <source media="(min-width: 800px)" srcset={fn.getThumbnail(photo.image.private_hash, 900)}>
                    <source media="(min-width: 500px)" srcset={fn.getThumbnail(photo.image.private_hash, 600)}>
                    <source media="(min-width: 300px)" srcset={fn.getThumbnail(photo.image.private_hash, 400)}>
                    <img src="{fn.getThumbnail(photo.image.private_hash, 900)}" alt="{photo.name}, {photo.location.name}, {photo.location.country.name}">
                </picture>
                {/each}
            </div>

            <div class="carousel__controls">
                <div class="carousel__controls--area prev" data-to="prev" on:mouseenter={hover} on:mouseleave={hover} on:click={goToPrev}>
                    <button class="button-control button-control--white dir-left" aria-label="Previous">
                        <IconArrow direction="left" color="#ff6c89" class="icon" />
                        <IconArrow direction="left" color="#fff" class="icon" hidden="true" />
                    </button>
                </div>

                <div class="carousel__controls--area next" data-to="next" on:mouseenter={hover} on:mouseleave={hover} on:click={goToNext}>
                    <button class="button-control button-control--white dir-right" aria-label="Next">
                        <IconArrow direction="right" color="#ff6c89" class="icon" />
                        <IconArrow direction="right" color="#fff" class="icon" hidden="true" />
                    </button>
                </div>
            </div>

            {#if viewer}
            <div class="carousel__number">
                {currentIndex < 10 ? 0 : ''}{photos.length - currentIndex}
            </div>
            {/if}
        </div>

        <div class="carousel__infos">
            <div class="carousel__infos--locations">
                {#each photos as photo, index}
                <div class="carousel__infos--location style-location"
                    class:prev={photo === prevPhoto}
                    class:active={photo === currentPhoto}
                    class:next={photo === nextPhoto}
                >
                    <p class="street">{photo.name}</p>
                    <p class="state style-caps style-caps--transparent">
                        {photo.location.name}, {photo.location.country.name}
                    </p>
                </div>
                {/each}
            </div>
            {#if viewer}
            <p class="carousel__infos--date">{dayjs(currentPhoto.created_on).format('MMM Do, YYYY')}</p>
            {/if}
        </div>

        {#if !viewer}
        <ol class="carousel__dots">
            {#each photos as page, index}
            <li class:active={page === currentPhoto} on:click={() => currentIndex = index}>
                <button aria-label="Go to photo #{index + 1}"></button>
            </li>
            {/each}
        </ol>
        {/if}
    </div>

    {#if viewer}
    <ol class="carousel__dots">
        {#each photos as page}
        <li class:active={page === currentPhoto}>
            <button></button>
        </li>
        {/each}
    </ol>
    {/if}
</div>
