(function( $ ) {
    
    let $btnPreviousWeek = $( '[data-prev-week]' ),
        $btnNextWeek = $( '[data-next-week]' ),
        $btnResyncWeek = $( '[data-sync-this-week]' ),
        $inputDateOfWeek = $( '[data-date-of-week]' );

    let currentURL = new URL( window.location.href.split('#')[0] );

    $( function () {
        console.log( currentURL.href );
    });

    $inputDateOfWeek.on( 'change', function () {
        let $this = $(this);

        currentURL.searchParams.delete('date-of-week');
        currentURL.searchParams.append( 'date-of-week' , $this.val());

        window.location.href = currentURL.href;
    } );

    $btnPreviousWeek.on( 'click', function () {
        let date = new Date( Date.parse( $inputDateOfWeek.val() ) );
        let prevWeekDate = new Date( date.setDate( date.getDate() - 7 ) );
        let prevWeekDateString = window.uind.utils.getFormattedDateAsISO8601( prevWeekDate );

        currentURL.searchParams.delete('date-of-week');
        currentURL.searchParams.append( 'date-of-week' , prevWeekDateString );

        window.location.href = currentURL.href;
    } );

    $btnNextWeek.on( 'click', function () {
        let date = new Date( Date.parse( $inputDateOfWeek.val() ) );
        let nextWeekDate = new Date( date.setDate( date.getDate() + 7 ) );
        let nextWeekDateString = window.uind.utils.getFormattedDateAsISO8601( nextWeekDate );

        currentURL.searchParams.delete('date-of-week');
        currentURL.searchParams.append( 'date-of-week' , nextWeekDateString );

        window.location.href = currentURL.href;
    } );

    $btnResyncWeek.on( 'click', function () {
        let date = new Date( Date.parse( $inputDateOfWeek.val() ) );
        console.log( date.getDate() );
        console.log( date.getDay() );
        let startDate = new Date( date.setDate( date.getDate() - date.getDay() + 1 ) );
        console.log( startDate );
        let endDate = new Date( date.setDate( startDate.getDate() + 6 ) );
        console.log( endDate );

        let startDateString = window.uind.utils.getFormattedDateAsISO8601( startDate );
        let endDateString = window.uind.utils.getFormattedDateAsISO8601( endDate );

        currentURL.searchParams.delete('date-of-week');

        console.log( ( currentURL.href + '/sync?from-date=' + startDateString + '&to-date=' + endDateString ).replace( '//sync', '/sync' ) );

        window.location.href = ( currentURL.href + '/sync?from-date=' + startDateString + '&to-date=' + endDateString ).replace( '//sync', '/sync' );
    } );

}( jQuery ));