<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"
      xmlns:tal="http://xml.zope.org/namespaces/tal"
      xmlns:metal="http://xml.zope.org/namespaces/metal"
      xmlns:i18n="http://xml.zope.org/namespaces/i18n"
      lang="en"
      metal:use-macro="context/main_template/macros/master"
      i18n:domain="xmldirector.plonecore">
<body>

<metal:main fill-slot="main">

    <link rel="stylesheet" type="text/css" tal:attributes="href string:$portal_url/++resource++xmldirector.plonecore/icons.css" />

    <div>
        <label i18n:translate="">Path</label>:            
        <span id="subpath">
            <tal:loop repeat="d options/subpath_components"><a tal:attributes="href d/href" tal:content="d/title"/>/</tal:loop>
        </span>
    </div>
    
    <div class="left" style="float: left; vertical-align: top">
        <input placeholder="Filter..." 
            id="query"
            type="text"
            onpaste="onFilterChanged(this.value)"
            oninput="onFilterChanged(this.value)"
            onchange="onFilterChanged(this.value)"
            onchange="onFilterChanged(this.value)"
            onkeydown="onFilterChanged(this.value)"
            onkeyup="onFilterChanged(this.value)"
        />
        <input id="reset-query" type="button" i18n:attributes="value" value="Clear query">
    </div>
    <div id="able-actions" style="float: right; vertical-align: bottom">
        <button class="action-create-collection " name="action-create-collection" i18n:translate="">Create Collection</button>
        <button class="action-import" name="action-import" i18n:translate="">Import</button>
        <button class="action-refresh" name="action-refresh" i18n:translate="">Refresh</button>
    </div>
    <div style="clear: both"></div>

    <div id="table-info"></div>
    <div id="myGrid" style="height: 500px;" class="ag-fresh"></div>

    <script type="text/javascript" tal:content="string: var URL = '${context/absolute_url}'"></script>
    <script type="text/javascript" 
        tal:define="subpath python: options.get('subpath', '')"
        tal:content="string: var SUBPATH = '${subpath}'"></script>

    <script type="text/javascript">

        function ajax_success(result) {
            $('#table-info').removeClass('status-ok status-error').addClass('status-ok');
            $('#table-info').text(result).stop(true, true).show().fadeOut(5000);
            set_subpath(SUBPATH);
            clear_query();
            DATA.length = 0;
            refresh_table();
        }
        
        function ajax_error(result) {
            $('#table-info').removeClass('status-ok status-error').addClass('status-error');
            $('#table-info').text(result.responseText).stop(true, true).show().fadeOut(5000);
        }

        function set_subpath(subpath) {
            var result = '';
            var items = subpath.split('/');
            var items_seen =  [];
            for (var i=0; i<items.length; i++)    {
                var item = items[i];
                items_seen.push(item)
                var url = sprintf('%s/@@view/%s', URL, items_seen.join('/'));
                result += sprintf('<a href="%s">%s</a>', url , item);
                if (i != items.length)
                    result += '/';
            }
            $('#subpath').html(result);
        }

        $('body').on('click', '.action-chdir', function(e) {
            e.preventDefault();
            SUBPATH = $(this).data('subpath');
            if (SUBPATH.indexOf('/') == 0)
                SUBPATH = SUBPATH.substring(1, SUBPATH.length);
            url = sprintf("%s/@@view/%s",URL, SUBPATH);
            var state = {url: url, subpath: SUBPATH} 
            window.history.pushState(state, null, url);
            set_subpath(SUBPATH);
            DATA.length = 0;
            refresh_table();
            gridOptions.api.setSortModel([]);
        });

        $('body').on('click', '.action-download', function(e) {
            e.preventDefault();
            var fullpath = $(this).data('fullpath');
            var url = sprintf("%s/@@filemanager-download?filename:utf8:ustring=%s", URL, fullpath);
            window.location.href = url;
        });

        $('body').on('click', '.action-zip-download', function(e) {
            e.preventDefault();
            var fullpath = $(this).data('fullpath');
            var url = sprintf("%s/@@filemanager-zip-download?subpath:utf8:ustring=%s", URL, fullpath);
            window.location.href = url;
        });

        $('.action-refresh').on('click', function(e) {
            e.preventDefault();
            DATA.length = 0;
            refresh_table();
        });

        $('body').on('click', '.action-import', function(e) {
            var url = sprintf("%s/@@connector-zip-import?subpath=%s", URL, SUBPATH)
            window.location.href = url;
        });
        
        $('body').on('click', '.action-create-collection', function(e) {
            e.preventDefault();
            var new_id = window.prompt('Create new collection');
            if (new_id != null) {
                var url = sprintf('%s/@@filemanager-create-collection', URL);
                $.ajax({
                    type: 'GET',
                    url: url,
                    data: {
                        'subpath:utf8:ustring': SUBPATH,
                        'new_id:utf8:ustring': new_id
                    },
                    success: ajax_success,
                    error: ajax_error
                });
            }
        });
        
        $('body').on('click', '.action-rename', function(e) {
            e.preventDefault();
            var title = $(this).data('title');
            var fullpath = $(this).data('fullpath');
            
            var new_id = window.prompt(msg, title);
            var url = sprintf('%s/@@filemanager-rename', URL);
            if (new_id != null) {
                $.ajax({
                    type: 'GET',
                    url: url,
                    data: {
                        'subpath:utf8:ustring': SUBPATH,
                        'old_id:utf8:ustring': title,
                        'new_id:utf8:ustring': new_id
                    },
                    success: ajax_success,
                    error: ajax_error
                });
            }
        });
        
        $('body').on('click', '.action-delete', function(e) {
            e.preventDefault();
            var title = $(this).data('title');
            var subpath = $(this).data('subpath');
            var id = $(this).data('id');
            var msg = sprintf('Do you really want to delete "%s/%s" to', subpath, id);
            if (confirm(msg)) {
                var url = sprintf('%s/@@filemanager-delete', URL);
                $.ajax({
                    type: 'GET',
                    url: url,
                    data: {
                        'subpath:utf8:ustring': SUBPATH,
                        'id:utf8:ustring': id
                    },
                    success: ajax_success,
                    error: ajax_error
                });
            }
        });

        $('#reset-query').on('click', function() {
            clear_query();
        });

        function clear_query() {
            $('#query').val("");
            $('#query').trigger("change");
        }

        /* Render title entries */
        function title_renderer(params) {
            var item = params.node.data;
            var url = item['url'];
            var title = item['title'];
            var fullpath = item['fullpath'];
            var type = item['type'];
            var ext = item['ext'];
            var s = '';
                
            var title = item['title'];
            if (item['type'] == 'directory') {
                s += sprintf('<a class="type-%s action-chdir" data-subpath="%s" data-ext="">%s</a>', type, fullpath, title);
                if (title != '..') {
                    s += sprintf('<a class="action-delete" title="Remove" data-subpath="%s" data-id="%s">', SUBPATH, title);
                    s += '<img src="++resource++xmldirector.plonecore/images/remove.png" title="Remove collection"/>'
                    s += '</a>';
                    s += sprintf('<a title="Rename" class="action-rename" data-fullpath="%s" data-title="%s"><img src="++resource++xmldirector.plonecore/images/rename.png" ></a>', fullpath, title);
                    s += sprintf('<a title="ZIP Download" class="action-zip-download" data-fullpath="%s" data-title="%s"><img src="++resource++xmldirector.plonecore/images/zip.png" ></a>', fullpath, title);
                        }
                return s;
            } else {
                var remove_url = item['remove_url'];
                var editable = item['editable'];
                s += sprintf('<a target="_new" class="type-%s" href="%s" data-ext="%s">%s</a>', type, url, ext, title);
                s += sprintf('\
                            <a class="action-delete" title="Remove" data-subpath="%s" data-id="%s">\
                            <img src="++resource++xmldirector.plonecore/images/remove.png" title="Remove item" i18n:attributes="title"/> </a>', 
                        SUBPATH, title);
                s += sprintf('<a title="Rename" class="action-rename" data-fullpath="%s" data-title="%s"><img src="++resource++xmldirector.plonecore/images/rename.png" ></a>', fullpath, title);
                s += sprintf('<a title="Download" class="action-download" data-fullpath="%s" data-title="%s"><img src="++resource++xmldirector.plonecore/images/download.png" ></a>', fullpath, title);
                if (editable) {
                    var edit_url = item['edit_url'];
                s += sprintf('<a href="%s" title="Edit" class="action-edit" ><img src="++resource++xmldirector.plonecore/images/edit.png" /></a>', edit_url);
                }
                return s;
            }
                ;
            return s;
        }

        /* Render modified entries */
        function modified_renderer(params) {
            if (params.node.data['title'] != '..') 
                return params.node.data['modified'];
            return '';
        }

        /* Render size entries */
        function size_renderer(params) {
            if (params.node.data['type'] == 'file') 
                return params.node.data['size'];
            return '[DIR]';
        }

        /* cmp() for modified */
        function modified_cmp(idx1, idx2) {
            function _modified(idx) {
                var size = 0
                try { modified = DATA[idx]['modified_original'];
                } catch(e) { modified = 0; }
                if (modified == undefined) modified = 0;
                return modified;
            }

            var m1 = _modified(idx1); var m2 = _modified(idx2);
            if (m1 < m2) return -1;
            if (m1 > m2) return 1;
            return 0;
        }

        /* cmp() for size */
        function size_cmp(idx1, idx2) {
            function _size(idx) {
                var size = 0
                try { size = DATA[idx]['size_original'];
                } catch(e) { size = 0; }
                if (size == undefined) size = -1;
                return size;
            }

            var s1 = _size(idx1); var s2 = _size(idx2);
            if (s1 < s2) return -1;
            if (s1 > s2) return 1;
            return 0;
        }


        function onFilterChanged(value) {
            gridOptions.api.setQuickFilter(value);
        }

        /* global array holding all directory and file rows */
        var DATA = new Array();

        function get_data(filter) {
            var url = URL + "/@@connector-folder-contents?subpath=" + SUBPATH;
            if (DATA.length == 0) {
                $.ajax({
                    url: url,
                    dataType: 'json',
                    async: false,
                    method: 'GET',
                    success: function(result) {
                        DATA.push.apply(DATA, result['dirs']);
                        DATA.push.apply(DATA, result['files']);

                        /* Update #collection-list */
                        if (result['dirs'].length > 0) {
                            var select = $('#collection-list');
                            $(result['dirs']).each(function(index, d) {
                                if (d['title'] != '..') 
                                    select.append(sprintf('<option value="%s">%s</option>', d['title'], d['title']));
                            });
                            if (select.find('option').length == 0)
                                $('#action-rename-collection').remove();
                        } else {
                            $('#action-rename-collection').remove();
                        }
                        
                        if (DATA.length == 0) {
                            $('#table').fadeOut();
                            $('#no-data').fadeIn();
                        } else {
                            $('#table').fadeIn();
                            $('#no-data').fadeOut();
                        }
                    } 
                });
            }
        }

    var columnDefs = [
        { headerName: "File/Directory", 
          field: 'title',
          width: 600, 
          cellRenderer: title_renderer,
          filter: 'text',
          suppressFilter: true
        },
        { headerName: "Modified",
          field: 'index', 
          width: 150, 
          cellClass: ['cell-center'],
          cellRenderer: modified_renderer,
          comparator: modified_cmp,
          suppressFilter: true
        },
        { headerName: "Size", 
          field: 'index',
          width: 100, 
          cellClass: ['cell-center'],
          cellRenderer: size_renderer,
          comparator: size_cmp,
          suppressFilter: true
        },
    ];


    var pageSize = 200;

    var localeText = {

    };

    var gridOptions = {
        // note - we do not set 'virtualPaging' here, so the grid knows we are doing standard paging
        enableSorting: true,
        enableFilter: true,
        enableColResize: true,
        columnDefs: columnDefs,
        rowModelType: 'pagination',
        rowHeight: 40,
        localeText: localeText
    };

    function onPageSizeChanged(newPageSize) {
        pageSize = new Number(newPageSize);
        createNewDatasource();
    }

    var allOfTheData;

    function createNewDatasource() {
        if (!allOfTheData) {
            // in case user selected 'onPageSizeChanged()' before the json was loaded
            return;
        }

        var dataSource = {
            //rowCount: ???, - not setting the row count, infinite paging will be used
            pageSize: pageSize, // changing to number, as scope keeps it as a string
            getRows: function (params) {
                // this code should contact the server for rows. however for the purposes of the demo,
                // the data is generated locally, a timer is used to give the experience of
                // an asynchronous call
                console.log('asking for ' + params.startRow + ' to ' + params.endRow);
                setTimeout( function() {
                    // take a chunk of the array, matching the start and finish times
                    var rowsThisPage = allOfTheData.slice(params.startRow, params.endRow);
                    // see if we have come to the last page. if we have, set lastRow to
                    // the very last row of the last page. if you are getting data from
                    // a server, lastRow could be returned separately if the lastRow
                    // is not in the current page.
                    var lastRow = -1;
                    if (allOfTheData.length <= params.endRow) {
                        lastRow = allOfTheData.length;
                    }
                    params.successCallback(rowsThisPage, lastRow);
                }, 500);
            }
        };

        gridOptions.api.setDatasource(dataSource);
    }


    function setRowData(rowData) {
        allOfTheData = rowData;
        createNewDatasource();
    }

    function refresh_table() {
        get_data();
        setRowData(DATA);
        gridOptions.api.sizeColumnsToFit();
    }

    $(document).ready(function() {
        var eGridDiv = document.querySelector('#myGrid');
        new agGrid.Grid(eGridDiv, gridOptions);
        refresh_table();
    });

    /* Restore window state based on stored History state */
    window.onpopstate  = function(event) {
        try {
            SUBPATH = event.state['subpath'];
        } catch(e) {
            SUBPATH = '';
        }
        DATA.length = 0;
        refresh_table();
    }

    </script>

</metal:main>

</body>
</html>

