{% extends "base.html" %}
{% block main_content %}
    <div id="contextMenu" class="dropdown-menu" role="menu" style="display:none" >
        <div id="dd_file_details" class="dropdown-header" href="#">Details...</div>
        <a class="dropdown-item" href="#">View File</a>
        <div class="dropdown-divider"></div>
        <a id="dd_move" class="dropdown-item" href="#">Move selected file(s) to new storage folder</a>
        <a id="dd_del" class="dropdown-item" href="#">Delete Selected file(s)</a>
    </div>

    <div class="container-fluid">
        <form method="POST"">
            {% if search_term is defined %}
                <input type="hidden" name="term" id="view_term" value="{{search_term}}">
            {% endif %}
            <div class="row">
                <div class="input-group col-lg-4">
                    {{CreateSelect( "noo", noo, ["Oldest", "Newest"], "$('#offset').val(0)")|safe }}
                    {{CreateSelect( "how_many", how_many, ["10", "25", "50", "75", "100", "150", "200", "500"])|safe }}
                    <span style="border:0" class="sm-txt my-auto h-100 btn btn-outline-info disabled">grouped by:</span>
                    {{CreateSelect( "grouping", grouping, ["None", "Day", "Week", "Month"])|safe }}
                </div class="input-group">
                {% if search_term is defined %}
                    <div class="col my-auto">
                        <span class="alert alert-primary">Searched for: '{{search_term}}'</span>
                    </div class="col my-auto">
                {% endif %}
                <div class="col my-auto d-flex justify-content-end">
                    <button id="prev" name="prev" class="sm-txt btn btn-info"><i class="fas fa-arrow-alt-circle-left"></i></button>
                    <span class="sm-txt h-100 my-auto">&nbsp;{{how_many}} files&nbsp;</span>
                    <button id="next" name="next" class="sm-txt btn btn-info"><i class="fas fa-arrow-alt-circle-right"></i></button>
                </div>
                <div class="col my-auto">
                    <button id="move" name="move" class="sm-txt btn btn-primary ml-4" onClick="MoveDBox(); return false;"><i class="fas fa-folder-plus"></i></button>
                    <button id="del" name="del" class="sm-txt btn btn-danger mx-1" onClick="DelDBox(); return false;"> <i class="far fa-trash-alt"></i> </button>
                </div>
                <div class="input-group col-lg-3 justify-content-end">
                    <div class="input-group-prepend">
                        <button style="width:98%" class="sm-txt btn btn-outline-info disabled" disabled>Size:</button>
                    </div>
                    {% if size == "64" %}
                        {% set bt="btn-info" %}
                    {% else %}
                        {% set bt="btn-outline-info" %}
                    {% endif %}
                    <div class="input-group-append">
                        <button id="64" class="sm-txt sz-but btn {{bt}}" onClick="ChangeSize(this,64); return false;">XS</button>
                    </div>
                    {% if size == "96" %}
                        {% set bt="btn-info" %}
                    {% else %}
                        {% set bt="btn-outline-info" %}
                    {% endif %}
                    <div class="input-group-append">
                        <button id="96" class="sm-txt sz-but btn {{bt}}" onClick="ChangeSize(this,96); return false;">S</button>
                    </div>
                    {% if size == "128" %}
                        {% set bt="btn-info" %}
                    {% else %}
                        {% set bt="btn-outline-info" %}
                    {% endif %}
                    <div class="input-group-append">
                        <button id="128" class="sm-txt sz-but btn {{bt}}" onClick="ChangeSize(this,128); return false;">M</button>
                    </div>
                    {% if size == "192" %}
                        {% set bt="btn-info" %}
                    {% else %}
                        {% set bt="btn-outline-info" %}
                    {% endif %}
                    <div class="input-group-append">
                        <button id="192" class="sm-txt sz-but btn {{bt}}" onClick="ChangeSize(this,192); return false;">L</button>
                    </div>
                    {% if size == "256" %}
                        {% set bt="btn-info" %}
                    {% else %}
                        {% set bt="btn-outline-info" %}
                    {% endif %}
                    <div class="input-group-append">
                        <button id="256" class="sm-txt sz-but btn {{bt}}" onClick="ChangeSize(this,256); return false;">XL</button>
                    </div>
                </div class="input-group">
            </div class="form-row">
            <input id="offset" type="hidden" name="offset" value="{{offset}}">
            <input id="size" type="hidden" name="size" value="{{size}}">
        </form>

        {% set last = namespace(printed=0) %}
        {% if grouping == "None" %}
            <div class="row pl-3">
        {% endif %}
        {% for obj in entry_data %}
            {% if grouping == "Day" %}
                {% if last.printed != obj.file_details[0].day %}
                    {% if last.printed > 0 %}
                        </div>
                    {% endif %}
                    <div class="row pl-3"><h6>Day: {{obj.file_details[0].day}} of {{obj.file_details[0].month}}/{{obj.file_details[0].year}}</h6></div>
                    <div class="row pl-3">
                    {% set last.printed = obj.file_details[0].day %}
                {% endif %}
            {% elif grouping == "Week" %}
                {% if last.printed != obj.file_details[0].woy %}
                    {% if last.printed > 0 %}
                        </div>
                    {% endif %}
                    <div class="row pl-3"><h6>Week #: {{obj.file_details[0].woy}} of {{obj.file_details[0].year}}</h6></div>
                    <div class="row pl-3">
                    {% set last.printed = obj.file_details[0].woy %}
                {% endif %}
            {% elif grouping == "Month" %}
                {% if last.printed != obj.file_details[0].month %}
                    {% if last.printed > 0 %}
                        </div>
                    {% endif %}
                    <div class="row pl-3"><h6>Month: {{obj.file_details[0].month}} of {{obj.file_details[0].year}}</h6></div>
                    <div class="row pl-3">
                    {% set last.printed = obj.file_details[0].month %}
                {% endif %}
            {% endif %}
            {% if obj.type.name != "Directory" %}
                    <figure id="{{obj.id}}" img="{{loop.index-1}}" class="figure mx-1" fname="{{obj.name}}" yr="{{obj.file_details[0].year}}" date="{{obj.file_details[0].year}}{{"%02d" % obj.file_details[0].month}}{{"%02d" % obj.file_details[0].day}}" details="{{obj.name}} (Date: {{obj.file_details[0].day}}/{{obj.file_details[0].month}}/{{obj.file_details[0].year}})">
                        {% if obj.type.name=="Image" %}
                            <a href="{{obj.in_dir[0].path_prefix}}/{{obj.name}}"><img class="thumb" height="{{size}}" src="data:image/jpeg;base64,{{obj.file_details[0].thumbnail}}"></img></a>
                        {% elif obj.type.name == "Video" %}
                            <div style="position:relative; width:100%">
                                <a href="{{obj.in_dir[0].path_prefix}}/{{obj.name}}"><img class="thumb" style="display:block" height="{{size}}" src="data:image/jpeg;base64,{{obj.file_details[0].thumbnail}}"></img></a>
                                <div style="position:absolute; top: 2; left: 2;">
                                    <i style="font-size:32;background-color:black;color:white" class="fas fa-film"></i>
                                </div>
                            </div>
                        {% endif %}
                        {# finding text distracting, <figcaption style="font-size:12px;" class="figure-caption text-center">{{obj.name}}</figcaption> #}
                    </figure>
            {% endif %}
        {% endfor %}
        {% if grouping == "None" %}
            </div class="row pl-3">
        {% endif %}
	</div class="container">
{% endblock main_content %}
{% block script_content %}
<script>

function GetSelnAsDiv()
{
    seln=''
    $('.highlight').each(function( index ) { 
        seln+='<div fname="' + $(this).attr('fname') + '" yr="' + $(this).attr('yr') +
            '" date="' + $(this).attr('date') +
            '" class="px-1 mx-1">' + $(this).children().html() + '</div>'
        } )
    return '<div class="row col-lg-12">'+seln+'</div>'
}

function DelDBox()
{
    $('#dbox-title').html('Delete Selected File(s)')  
    div =`
        <div class="row col-lg-12">
        <p class="col">Delete the following files?</p>
        </div>`
    div+=GetSelnAsDiv()
    div+=`
        <div class="row col-lg-12">
            <button onClick="$('#dbox').modal('hide')" class="btn btn-outline-secondary col-lg-2">Cancel</button>
            <button onClick="$('#dbox').modal('hide');alert('not yet');" class="btn btn-outline-danger col-lg-2">Ok</button>
        </div>
    `
    $('#dbox-content').html(div)
    $('#dbox').modal('show')
}

function MoveDBox()
{
    $('#dbox-title').html('Move Selected File(s) to new directory in Storage Path')  
    div =`
        <div class="form-row col-lg-12">
        <p class="col">Moving the following files?</p>
        </div>`
    div+=GetSelnAsDiv()
    yr=$('.highlight').first().attr('yr')
    dt=$('.highlight').first().attr('date')
    div+=`
        <form class="form form-control-inline col-lg-12" method="POST" action="/move_files">
        <div class="input-group col-lg-12">
        <input type="text" name="prefix" class="input-group-prepend col-lg-2 form-control-plaintext text-right" value="To: 
        `
    div+=yr+'/'+dt+"-"
    div+=`"></input>
        <input type="text" name="suffix" class="col-lg-3 form-control" placeholder="name"> </input>
        </div>
        <br>
        <div class="form-row col-lg-12">
            <button onClick="$('#dbox').modal('hide'); return false;" class="btn btn-outline-secondary offset-lg-1 col-lg-2">Cancel</button>
            <button onClick="$('#dbox').modal('hide'); console.log("should do the move one day"); return false;" class="btn btn-outline-primary col-lg-2">Ok</button>
        </div>
        </form>
    `
    $('#dbox-content').html(div)
    $('#dbox').modal('show')
}

function ChangeSize(clicked_button,sz)
{
	$('.sz-but.btn-info').removeClass('btn-info').addClass('btn-outline-info')
	$(clicked_button).addClass('btn-info').removeClass('btn-outline-info')
	$('.thumb').attr( {height: sz, style: 'font-size:'+sz } )
	$('#size').val(sz)
}

// e == event (can see if shift/ctrl held down while left-clicking
// el == element the click is on
// this allows single-click to select, ctrl-click to (de)select 1 item, and
// shift-click to add all elements between highlighted area and clicked area,
// whether you click after highlight or before
function DoSel(e, el)
{
    if( e.ctrlKey )
    {
        $(el).toggleClass('highlight')
        return
    }
    if( e.shiftKey )
    {
        st=Number($('.highlight').first().attr('img'))
        end=Number($('.highlight').last().attr('img'))
        clicked=Number($(el).attr('img'))
        if( clicked > end )
            $('.figure').slice( end, clicked+1 ).addClass('highlight')
        else
            $('.figure').slice( clicked, st ).addClass('highlight')
        return
    }
    $('.highlight').removeClass('highlight')
    $(el).addClass('highlight')
}

$('.figure').click( function(e) { DoSel(e, this ); return false; });

(function ($, window) {

    $.fn.contextMenu = function (settings) {

        return this.each(function () {

            // Open context menu
            $(this).on("contextmenu", function (e) {
                // return native menu if pressing control
                if (e.ctrlKey) return;

                fd=$(e.target).closest(".figure").attr('details')
                $('#dd_file_details').text(fd)
                //open menu
                var $menu = $(settings.menuSelector)
                    .data("invokedOn", $(e.target))
                    .show()
                    .css({
                        position: "absolute",
                        left: getMenuPosition(e.clientX, 'width', 'scrollLeft'),
                        top: getMenuPosition(e.clientY, 'height', 'scrollTop')
                    })
                    .off('click')
                    .on('click', 'a', function (e) {
                        $menu.hide();
                        var $invokedOn = $menu.data("invokedOn");
                        var $selectedMenu = $(e.target);
                        settings.menuSelected.call(this, $invokedOn, $selectedMenu);
                    });
                return false;
            });

            //make sure menu closes on any click
            $('body').click(function () {
                $(settings.menuSelector).hide();
            });
        });
        
        function getMenuPosition(mouse, direction, scrollDir) {
            var win = $(window)[direction](),
                scroll = $(window)[scrollDir](),
                menu = $(settings.menuSelector)[direction](),
                position = mouse + scroll;
            // opening menu would pass the side of the page
            if (mouse + menu > win && menu < mouse)
                position -= menu;
            return position;
        }

    };
})(jQuery, window);

$(".figure").contextMenu({
    menuSelector: "#contextMenu",
    menuSelected: function (invokedOn, selectedMenu) {
        var msg = "You selected the menu item '" + selectedMenu.text() +
            "' on the file id: " + $(invokedOn).parent().parent().attr('id')
        console.log(msg);
        if ( "View File" == selectedMenu.text() ) {
            document.location.href = $(invokedOn).parent().attr('href')
        }
    }
});

$(document).ready(function() {
    if( {{offset}} == 0 )
    {
        $('#prev').addClass('disabled')
        $('#prev').prop('disabled', true)
    }
} )
</script>
{% endblock script_content %}
