<script>
    import { createEventDispatcher, onMount } from 'svelte';
    import { scaleTime } from 'd3-scale';

    const dispatch = createEventDispatcher();

    export let column;
    export let textDirection;

    export let active;
    let points = [];

    onMount(() => {
        points = column
            .values()
            .map((val, i) => {
                return {
                    index: i,
                    date: val,
                    value: column.raw()[i]
                };
            })
            .sort((a, b) => {
                a.date.getTime() - b.date.getTime();
            });
    });

    function select(point) {
        $active = point.index;
        dispatch('change', point);
    }

    let totalWidth;
    $: width = totalWidth - 35;

    $: scale = scaleTime(
        // domain
        points.length > 0 ? [points[0].date, points[points.length - 1].date] : [],
        // range
        textDirection === 'rtl' ? [width, 0] : [0, width]
    );

    $: lastPointLeft = points.length > 0 ? scale(points[points.length - 1].date) : 0;
</script>

<style lang="scss">
    .filter-ui {
        height: 45px;
        margin-left: 3px;
        position: relative;

        .tick {
            position: absolute;
            color: inherit;
            text-decoration: none;

            .point {
                display: inline-block;

                cursor: pointer;
                position: absolute;

                z-index: 100;

                height: 20px;
                width: 20px;
                border-radius: 10px;
                top: 20px;
            }
        }

        .line {
            height: 1px;
            position: absolute;
            left: 0px;
            top: 30px;
            z-index: 1;
        }
    }
</style>

<nav class="filter-ui filter-timescale" bind:clientWidth={totalWidth}>
    {#each points as point}
        <a
            href="#/{point.index}"
            class="tick link-style-ignore"
            tabindex="0"
            on:click|preventDefault={() => select(point)}
            class:active={active === point.index}
            style:left={`${scale(point.date)}px`}
        >
            <div class="point" class:active={$active === point.index} />
            <div class="point-label">
                {point.value}
            </div>
        </a>
    {/each}

    <div class="line" style="width: {lastPointLeft}px" />
</nav>
